LeetCode: Unique Binary Search Trees II 解題報告

Unique Binary Search Trees II

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

For example,node

Given n = 3, your program should return all 5 unique BST's shown below.git

   1         3     3      2      1github

    \       /     /      / \      \ide

     3     2     1      1   3      2spa

    /     /       \                 \code

   2     1         2                 3blog

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.遞歸

 

Hide Tags Tree Dynamic Programmingleetcode

SOLUTION 1:

使用遞歸來作。

1. 先定義遞歸的參數爲左邊界、右邊界,即1到n.

2. 考慮從left, 到right 這n個數字中選取一個做爲根,餘下的使用遞歸來構造左右子樹。 

3. 當無解時,應該返回一個null樹,這樣構造樹的時候,咱們會比較方便,不會出現左邊解爲空,或是右邊解爲空的狀況。

4. 若是說左子樹有n種組合,右子樹有m種組合,那最終的組合數就是n*m. 把這全部的組合組裝起來便可

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; left = null; right = null; }
 8  * }
 9  */
10 public class Solution {
11     public List<TreeNode> generateTrees(int n) {
12         // 0.07
13         return dfs(1, n);
14     }
15     
16     public List<TreeNode> dfs(int left, int right) {
17         List<TreeNode> ret = new ArrayList<TreeNode>();
18         
19         // The base case;
20         if (left > right) {
21             ret.add(null);
22             return ret;
23         }
24         
25         for (int i = left; i <= right; i++) {
26             List<TreeNode> lTree = dfs(left, i - 1);
27             List<TreeNode> rTree = dfs(i + 1, right);
28             for (TreeNode nodeL: lTree) {
29                 for (TreeNode nodeR: rTree) {
30                     TreeNode root = new TreeNode(i);
31                     root.left = nodeL;
32                     root.right = nodeR;
33                     ret.add(root);
34                 }
35             }
36         }
37         
38         return ret;
39     }
40 }
View Code

 

CODE:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/72f914daab2fd9e2eb8a63e4643297d78d4fadaa/tree/GenerateTree2.java

相關文章
相關標籤/搜索