LeetCode 56 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
分析:

看见generate all 先想到了DFS,但没有找到图关系。

根据二叉树性质,每一个数作为根,再递归地对左右建二叉树即可。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; left = null; right = null; }
 * }
 */
public class Solution {
    public List generateTrees(int n) {
        return generateTrees(0, n-1);
    }
    
    public List generateTrees(int begin, int end){
        List res = new ArrayList();
        if(begin > end){
            res.add(null);
            return res;
        }
        //每一个数都当根节点
        for(int i=begin; i<=end; i++){
            //递归的对左右建树
            //这时可以认为左右所建的子树已经放在left,right里
            List left = generateTrees(begin, i-1);
            List right = generateTrees(i+1, end);
            //当前数为节点,并尝试左边的每一棵树和作为左子树
            //右边的每一棵树作为右子树
            for(int j=0; j


你可能感兴趣的:(LeetCode)