1. 程式人生 > >[leetcode]unique-binary-search-trees

[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;
    }
}