Skip to content

Latest commit

 

History

History
58 lines (47 loc) · 1.68 KB

95. Unique Binary Search Trees II.md

File metadata and controls

58 lines (47 loc) · 1.68 KB

96. Unique Binary Search Trees

Problem

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

tag:

Solution

以i为根节点的BST, 左子树包含1i-1, 右子树包含i+1n, 总的个数为左子树*右子树,对于给定区间start~end,其unique BST可以通过递归求解:

  • 节点数为0 返回空树
  • 节点数为1 返回 new TreeNode(i) 否则,针对区间内的每个数i,递归求解其左右子树,然后遍历左右子树,链接到以i为根节点的树上

java

    public List<TreeNode> generateTrees(int n) {
        if(n<1) return new ArrayList<TreeNode>();
        return helper(1,n);
    }
    
    List<TreeNode> helper(int start, int end) {
        List<TreeNode> res = new ArrayList<TreeNode>();
        if(start>end) {
            res.add(null);
            return res;
        }
        
        for(int i=start; i<=end; i++) {
            List<TreeNode> left = helper(start, i-1);
            List<TreeNode> right = helper(i+1, end);
            for(TreeNode l : left)
                for(TreeNode r : right) {
                    TreeNode root = new TreeNode(i);
                    root.left = l;
                    root.right = r;
                    res.add(root);
                }
        }
        return res;
    }