LeetCode Online Judge 题目C# 练习 - 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 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上。