标签:leetcode java unique binary search
Given n, generate all structurally unique BST‘s (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST‘s shown below.
1 3 3 2 1
\ / / / \ 3 2 1 1 3 2
/ / \ 2 1 2 3
给定n ,生成所有的存在且唯一的二叉搜索树来储存值1...n.
比如,
给定n = 3,你需要返回所有的5个二叉搜索树如下所示:
1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3
* 与《Unique Binary Search Trees》类似
* 不同之处在于:这道题比1难的就是不是返回个数,而是返回所有结果。
* 这道题的解题依据依然是:
* 当数组为 1,2,3,4,.. i,.. n时,基于以下原则的BST建树具有唯一性:
* 以i为根节点的树,其左子树由[1, i-1]构成, 其右子树由[i+1, n]构成。
* 在循环中调用递归函数求解子问题
<span style="font-family:Microsoft YaHei;font-size:12px;">/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public ArrayList<TreeNode> generateTrees(int n) { return generateTrees(1, n);//从1作为root开始,到n作为root结束 } private ArrayList<TreeNode> generateTrees(int left, int right) { ArrayList<TreeNode> res = new ArrayList<TreeNode>(); if (left > right) { res.add(null); return res; } for (int i = left; i <= right; i++) { ArrayList<TreeNode> lefts = generateTrees(left, i-1);//以i作为根节点,左子树由[1,i-1]构成 ArrayList<TreeNode> rights = generateTrees(i+1, right);//右子树由[i+1, n]构成 for (int j = 0; j < lefts.size(); j++) { for (int k = 0; k < rights.size(); k++) { TreeNode root = new TreeNode(i); root.left = lefts.get(j); root.right = rights.get(k); res.add(root);//存储所有可能行 } } } return res; } }</span>
版权声明:本文为博主原创文章,转载注明出处
[LeetCode][Java]Unique Binary Search Trees II
标签:leetcode java unique binary search
原文地址:http://blog.csdn.net/evan123mg/article/details/46966217