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         public static List<BSTNode> UniqueBinarySearchTreeII(int n)
 2         {
 3             return UniqueBinarySearchTreeIIHelper(1, n);
 4         }
 5 
 6         public static List<BSTNode> UniqueBinarySearchTreeIIHelper(int start, int end)
 7         {
 8             List<BSTNode> res = new List<BSTNode>();
 9             if(start > end)
10             { 
11                 res.Add(null);
12                 return res;
13             }
14             List<BSTNode> leftChild, rightChild;
15                 
16             for(int i=start; i<=end; i++)
17             {
18                 leftChild = UniqueBinarySearchTreeIIHelper(start,i-1);
19                 rightChild = UniqueBinarySearchTreeIIHelper(i+1,end);
20         
21                 foreach (var litem in leftChild)
22                 {
23                     foreach (var ritem in rightChild)
24                     {
25                         BSTNode root = new BSTNode(i);
26                         root.Left = litem;
27                         root.Right = ritem;
28                         res.Add(root);
29                     }
30                 }
31             }
32             return res;
33         }

代码分析:

  递归,分别求出左边,右边的subtree root,在二重循环把他们加到root上。

相关文章:

  • 2021-07-08
  • 2021-06-06
  • 2021-11-04
  • 2021-12-25
  • 2021-08-20
  • 2021-07-14
猜你喜欢
  • 2021-12-22
  • 2022-02-21
  • 2022-01-02
  • 2022-01-12
  • 2022-03-06
  • 2021-06-07
相关资源
相似解决方案