95. Unique Binary Search Trees II

来源:互联网 发布:诸神黄昏天梭进阶数据 编辑:程序博客网 时间:2024/06/05 18:57

Given an integer 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

代码实现

public class Solution {    public IList<TreeNode> GenerateTrees(int n) {        if (n == 0)            return new List<TreeNode>();        return binaryTrees(1,n);    }    private IList<TreeNode> binaryTrees(int start, int end){             IList<TreeNode> rtn = new List<TreeNode>();        if(start>end)         {            rtn.Add(null); //this line code is important!            return rtn;        }        for(int i=start; i<=end; i++){            //分而治之: [start,i-1] < i < [i+1, end], i is the val of root            IList<TreeNode> lefts = binaryTrees(start, i-1);            IList<TreeNode> rights = binaryTrees(i+1, end);            foreach(var leftNode in lefts){                foreach(var rightNode in rights){                    TreeNode root = new TreeNode(i);                    root.left = leftNode;                    root.right = rightNode;                    rtn.Add(root);                }            }        }        return rtn;     }}

leetcode-solution库

leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp

2 0
原创粉丝点击