[LeetCode] 95. Unique Binary Search Trees II(Java)

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

Example:

Input: 3
Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:

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

分析:

方法一:採用深度搜索方法,由於要構建二叉搜索樹,很顯然,我們把1,2,,,n. 當成一個數組來看,對於當前元素,數組左側元素即爲其左子樹的元素,數組右側元素爲其右子樹元素,採用深度搜索方式即可求得所有二叉搜索樹。

代碼:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<TreeNode> generateTrees(int n) {
        List<TreeNode> ans=new ArrayList<>();
        if(n==0){
            return ans;
        }
        helper(1,n,ans);
        return ans;
    }
    private void helper(int start,int end,List<TreeNode> ans){
        if(start>end){
            ans.add(null);
            return;
        }
        for(int i=start;i<=end;i++){
            List<TreeNode> left=new ArrayList<>();
            List<TreeNode> right=new ArrayList<>();
            helper(start,i-1,left);
            helper(i+1,end,right);
            for(int j=0;j<left.size();j++){
                for(int k=0;k<right.size();k++){
                    TreeNode root=new TreeNode(i);
                    root.left=left.get(j);
                    root.right=right.get(k);
                    ans.add(root);
                }
            }
        }
    }
}

 

發佈了21 篇原創文章 · 獲贊 8 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章