关闭

Unique Binary Search Trees II

标签: 二叉树
114人阅读 评论(0) 收藏 举报
分类:
  1. 问题

    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
    
  2. 解答
    class Solution {
    public:
        vector<TreeNode *> generate(int beg, int end)
        {
            vector<TreeNode* > ret;
            if (beg > end)
            {
                ret.push_back(NULL);
                return ret;
            }
            
            for(int i = beg; i <= end; i++)
            {
                vector<TreeNode* > leftTree = generate(beg, i - 1);
                vector<TreeNode* > rightTree = generate(i + 1, end);
                for(int j = 0; j < leftTree.size(); j++)
                    for(int k = 0; k < rightTree.size(); k++)
                    {
                        TreeNode *node = new TreeNode(i + 1);
                        ret.push_back(node);
                        node->left = leftTree[j];
                        node->right = rightTree[k];              
                    }           
            }
            
            return ret;
        }
        
        vector<TreeNode *> generateTrees(int n) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            return generate(0, n - 1);
        }
    };


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9822次
    • 积分:514
    • 等级:
    • 排名:千里之外
    • 原创:42篇
    • 转载:7篇
    • 译文:0篇
    • 评论:0条