即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

LeetCode | Unique Binary Search Trees II

编程语言 u012998115 9℃ 0评论
本文目录
[隐藏]

1.题目

Given an integer 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

2.思路

依次将每个数作为根节点,然后对根节点左边的数和右边的数做递归运算即可

3.代码

/**
 * 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 generateTrees(int n) {
        if(n == 0)
            return new ArrayList();
        return constructTrees(1,n);
    }
    public List constructTrees(int left,int right){
        if(left > right){
            List listTrees = new ArrayList();
            listTrees.add(null);
            return listTrees;
        }
        List listTrees = new ArrayList();  
        for(int i=left;i<=right;i++){
            List listLeftTrees = constructTrees(left,i-1);
            List listRightTrees = constructTrees(i+1,right);
            for(TreeNode leftNode:listLeftTrees){
                for(TreeNode rightNode:listRightTrees){
                    TreeNode rootNode = new TreeNode(i);
                    rootNode.left = leftNode;
                    rootNode.right = rightNode;
                    listTrees.add(rootNode);
                }
            }
       }
        return listTrees;
    }
}

转载请注明:CodingBlog » LeetCode | Unique Binary Search Trees II

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情