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.

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

 

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

 

Hide Tags Tree Dynamic Programming

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM