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

Solution1:

划分左右子树,递归构造

public List<TreeNode> generateTrees0(int n) {
    return generate(1, n);
}

public List<TreeNode> generate(int start, int end) {
    List<TreeNode> trees = new ArrayList<TreeNode>();
    if(start>end) {
        trees.add(null);
        return trees;
    }
    for(int i=start; i<=end; i++) {
        List<TreeNode> leftTrees = generate(start, i-1);
        List<TreeNode> rightTrees = generate(i+1, end);
        for(int j=0; j<leftTrees.size(); j++) {
            for(int k=0; k<rightTrees.size(); k++) {
                TreeNode root = new TreeNode(i);
                root.left = leftTrees.get(j);
                root.right = rightTrees.get(k);
                trees.add(root);
            }
        }
    }
    return trees;
}

 

Solution2:

用DP数组保存前面的结果。后面的计算在使用DP数组添加右子树的时候,需要加上root节点的值。

public List<TreeNode> generateTrees(int n) {
    List<TreeNode>[] trees = new List[n+1];
    trees[0] = new ArrayList<TreeNode>();
    trees[0].add(null);
    
    for(int i=1; i<=n; i++) {
        trees[i] = new ArrayList<TreeNode>();
        for(int j=0; j<i; j++) {
            List<TreeNode> leftTrees = trees[j];
            List<TreeNode> rightTrees = trees[i-j-1];
            for(TreeNode left: leftTrees) {
                for(TreeNode right: rightTrees) {
                    TreeNode root = new TreeNode(j+1);
                    root.left = left;
                    root.right = copy(right, j+1);
                    trees[i].add(root);
                }
            }
        }
    }
    return trees[n];
}

public TreeNode copy(TreeNode node, int offset) {
    if(node == null) return null;
    TreeNode newNode = new TreeNode(node.val+offset);
    newNode.left = copy(node.left, offset);
    newNode.right = copy(node.right, offset);
    return newNode;
}

 

你可能感兴趣的:(LeetCode - Unique Binary Search Trees II)