您的位置:首页 > 产品设计 > UI/UE

LeetCode Online Judge 题目C# 练习 - Unique Binary Search Trees II

2012-10-22 23:56 656 查看
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.

public static List<BSTNode> UniqueBinarySearchTreeII(int n)
{
return UniqueBinarySearchTreeIIHelper(1, n);
}

public static List<BSTNode> UniqueBinarySearchTreeIIHelper(int start, int end)
{
List<BSTNode> res = new List<BSTNode>();
if(start > end)
{
res.Add(null);
return res;
}
List<BSTNode> leftChild, rightChild;

for(int i=start; i<=end; i++)
{
leftChild = UniqueBinarySearchTreeIIHelper(start,i-1);
rightChild = UniqueBinarySearchTreeIIHelper(i+1,end);

foreach (var litem in leftChild)
{
foreach (var ritem in rightChild)
{
BSTNode root = new BSTNode(i);
root.Left = litem;
root.Right = ritem;
res.Add(root);
}
}
}
return res;
}


代码分析:

  递归,分别求出左边,右边的subtree root,在二重循环把他们加到root上。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: