[leetcode]unique-binary-search-trees

1.unique-binary-search-trees

问题描述:
Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?

For example,
Given n = 3, there are a total of 5 unique BST's.

  1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

思路:
定义一个ArrayList用于记录n个节点时不同结构树的个数,如record.get(i)=m,说明i个节点时有m种树的结构。先初始化当节点个数为0,1,2时,不同的结构为1,1,2,将这些数据添加到record中。从节点个数3开始遍历知道节点个数为n,当遍历到一个节点个数p时,计算出不同结构树的个数num,将其添加到record中。在计算这个个数的时候,我们利用到了record中现有的数据,从根节点为1遍历到根节点为i,相应的左子树个数为0到i-1,右子树为i-1到0。当左子树个数为m右子树个数为n时可以通过record.get(m)*record.get(n)获得,累加num,可得节点个数为p时不同结构树的个数。

代码:

public class Solution {
    public int numTrees(int n) {
        ArrayList<Integer> record=new ArrayList<Integer>();
        record.add(1);    //空的时候也有一种排序
        for(int i=1;i<3;i++){
            record.add(i);
        }
        for(int i=3;i<=n;i++){
            int num=0;
            for(int j=1;j<=i;j++){
                num=num+record.get(j-1)*record.get(i-j);
            }
            record.add(num);
        }
        return record.get(n);
    }
}

2.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

思路:
这题与上题不同的地方是要输出树的结构而不仅仅是不同结构的个数。
调用一个函数递归的生成树,传递的参数有两个,是根节点可以选择的范围start和end。当start<end时,返回一空树。否则,当前的根节点i从start遍历到end,其左/右子树调用函数生成,生成左子树传递的参数时(start,i-1),生成右子树传递的参数为(i+1,end)。函数返回的是一个泛型为TreeNode的ArrayList,两层循环遍历返回的两个ArrayList,从而生成左子树和右子树,将结果添加到result中,将result返回。

代码:

public class Solution {
    
    public ArrayList<TreeNode> generateTrees(int n) {
        
        return create(1,n);
    }
    
    public ArrayList<TreeNode> create(int start,int end){
        ArrayList<TreeNode> result=new ArrayList<TreeNode>();
        if(start>end){
            result.add(null);
            return result;
        }
        for(int i=start;i<=end;i++){
            ArrayList<TreeNode> l=create(start,i-1);
            ArrayList<TreeNode> r=create(i+1,end);
            for(TreeNode left:l){
                for(TreeNode right:r){
                    TreeNode root=new TreeNode(i);
                    root.left=left;
                    root.right=right;
                    result.add(root);
                }
            }
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41618373/article/details/83989582
今日推荐