Unique Binary Search Trees II
Unique Binary Tree 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
思路
找到一个数作为根结点,剩余的数分别划入左子树或者右子树。递归的思想
解题
c++版1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
return createTree(1,n);
}
vector<TreeNode*> createTree(int begin,int end){
vector<TreeNode *> results;
if(begin>end){
results.push_back(NULL);
return results;
}
for(int k=begin;k<=end;k++){
vector<TreeNode *> left=createTree(begin,k-1);
vector<TreeNode *> right=createTree(k+1,end);
for(int i=0;i<left.size();i++){
for(int j=0;j<right.size();j++){
TreeNode *root=new TreeNode(k);
root->left=left[i];
root->right=right[j];
results.push_back(root);
}
}
}
return results;
}
};
python版1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {integer} n
# @return {TreeNode[]}
def generateTrees(self, n):
return self.createTree(1,n);
def createTree(self,begin,end):
results=[]
if(begin>end):
results.append(None)
return results
for k in range(begin,end+1):
left=self.createTree(begin,k-1)
right=self.createTree(k+1,end)
for i in range(len(left)):
for j in range(len(right)):
root=TreeNode(k)
root.left=left[i]
root.right=right[j]
results.append(root);
return results