《leetCode》:Unique Binary Search Trees II

题目

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

思路

找到一个数作为根结点,剩余的数分别划入左子树或者右子树。
result of BSTs with k being the root
=root(k)+ result of BSTs of (1~k-1) numbers as leftSubTree +result of BSTs of (k+1~n) numbers as rightSubTree

实现代码如下:

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
public class Solution {
    public List<TreeNode> generateTrees(int n) {
        if(n<1){
            return new ArrayList<TreeNode>();
        }
        return generateTrees(1,n);  
    }
    //函数功能:树节点中的value由start~end构成的二叉搜索树的所有结果
    private List<TreeNode> generateTrees(int start, int end) {
        List<TreeNode> res=new ArrayList<TreeNode>();
        if(end<start){
            res.add(null);
            return res;
        }
        for(int i=start;i<=end;i++){
            //产生以i为根节点,start~i-1构成左子树,i+1~end构成右子树
            List<TreeNode> leftSubTreeList=generateTrees(start,i-1);
            List<TreeNode> rightSubTreeList=generateTrees(i+1,end);
            //遍历并由根节点组合左子树和右子树构成最后的结果
            for(TreeNode leftSubTree:leftSubTreeList){
                for(TreeNode rightSubTree:rightSubTreeList){
                    TreeNode root=new TreeNode(i);
                    root.left=leftSubTree;
                    root.right=rightSubTree;
                    res.add(root);
                }
            }
        }
        return res;
    }
}

从这两题可以看出,递归确实是一个难点。还是不能够理解其中的精髓。

你可能感兴趣的:(LeetCode,搜索,unique,search,binary)