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

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 *> getalltrees(int begin,int end)
    {
        vector<TreeNode *> result;
        if(begin>end)
        {
            result.push_back(NULL);
            return result;
        }
        vector<TreeNode *> lefttree;
        vector<TreeNode *> righttree;
        for(int i=begin;i<=end;i++)
        {
            lefttree=getalltrees(begin,i-1);
            righttree=getalltrees(i+1,end);
            for(int j=0;j<lefttree.size();j++)
            {
                for(int t=0;t<righttree.size();t++)
                {
                    TreeNode *root=new TreeNode(i+1);
                    root->left=lefttree[j];
                    root->right=righttree[t];
                    result.push_back(root);
                }
            }
        }
        return result;
    }
    vector<TreeNode *> generateTrees(int n) {
        vector<TreeNode *> result;
        result=getalltrees(0,n-1);
        return result;
    }
};


 

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