zoukankan      html  css  js  c++  java
  • LeetCode-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         3     3      2      1
               /     /      /       
         3     2     1      1   3      2
        /     /                        
       2     1         2                 3
    

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


    OJ's Binary Tree Serialization:

    The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

    Here's an example:

       1
      / 
     2   3
        /
       4
        
         5
    

    The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

    class Solution {
    public:
        vector<TreeNode *> generateTrees(int n) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            if(n==0){
                vector<TreeNode*> aaa;
                aaa.push_back(NULL);
                return aaa;
            }
            vector<vector<vector<TreeNode*> > > vec;
            vector<vector<TreeNode*> >one;
            for(int i=0;i<=n;i++){
                one.resize(n-i+1);
                vec.push_back(one);
            }
            for(int j=0;j<n;j++){
                vec[j][0].push_back(NULL);
                vec[j][1].push_back(new TreeNode(j+1));    
            }
            vec[n][0].push_back(NULL);
            for(int j=2;j<=n;j++){
                for(int i=0;i<=n-j;i++){
                    for(int k=0;k<j;k++){
                        for(int l=0;l<vec[i][k].size();l++){
                            for(int r=0;r<vec[i+k+1][j-k-1].size();r++){
                                TreeNode* root=new TreeNode(i+k+1);
                                root->left=vec[i][k][l];
                                root->right=vec[i+k+1][j-k-1][r];
                                vec[i][j].push_back(root);
                            }
                        }
                    }
                }
            }
            return vec[0][n];
        }
    };
    View Code
  • 相关阅读:
    Hive内部表外部表转化分析
    20130515
    mapred.local.dir
    经典
    hive中巧用正则表达式的贪婪匹配
    做生意十大忌
    股价是最没有用的东西,要看公司基本面和盈利
    textView文本不同颜色
    Android中扫描wifi热点
    android 与 PC的socket通信
  • 原文地址:https://www.cnblogs.com/superzrx/p/3351396.html
Copyright © 2011-2022 走看看