程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> [leetcode]Unique Binary Search Trees II

[leetcode]Unique Binary Search Trees II

編輯:C++入門知識

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


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<TreeNode *> generateSub(int N, int start){
        if(N == 0){
            //   return vector<TreeNode *>(1, NULL);
            vector<TreeNode*> tmp;
            tmp.push_back(NULL);
            return tmp;
        }
         
        
       vector<TreeNode *> curLeft, curRight, result;
        for(int n = 1; n <= N; n++){
            int rootval = n + start - 1;
            
            curLeft = generateSub(n-1, start);
            curRight = generateSub(N-n, rootval+1);
            
            for(int i = 0; i < curLeft.size(); i++){
                for(int j = 0; j < curRight.size(); j++){
                    TreeNode *root = new TreeNode(rootval);
                    root -> left = curLeft[i];
                    root -> right = curRight[j];
                    
                    result.push_back(root);
                }
            } 
        }
    
        return result;
    }

    vector<TreeNode *> generateTrees(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        return generateSub(n, 1);
        
    }
};

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved