Unique Binary Search Trees II(不同的二叉查找树 II)

问题

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

Have you met this question in a real interview? Yes
Example
Given n = 3, your program should return all 5 unique BST's shown below.

Unique Binary Search Trees II(不同的二叉查找树 II)_第1张图片

分析

互相参阅 Unique Binary Search Trees(不同的二叉查找树)
需要注意两点:
1,使用递归来实现。
2,当start>end时,一定要加一个null,否则不会产生节点。

代码

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @paramn n: An integer
     * @return: A list of root
     */
    public List generateTrees(int n) {
        // write your code here
        return tree(1,n);
    }
    private List tree(int start,int end){
        List list=new ArrayList();
        if(start>end){
            list.add(null);
            return list;
        }
        for(int i=start;i<=end;i++){
            for(TreeNode left:tree(start,i-1)){
                for(TreeNode right:tree(i+1,end)){
                    TreeNode node=new TreeNode(i);
                    node.left=left;
                    node.right=right;
                    list.add(node);
                }
            }
        }
        return list;
    }
}

你可能感兴趣的:(Unique Binary Search Trees II(不同的二叉查找树 II))