标签:
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.
[Solution]
1 vector<TreeNode *> generateTrees(int n) 2 { 3 return BSTGenerate(1, n); 4 } 5 6 vector<TreeNode *> BSTGenerate(int start, int end) 7 { 8 TreeNode *root = NULL; 9 vector<TreeNode *> left_trees, right_trees, trees; 10 if (start > end) 11 { 12 trees.push_back(NULL); 13 return trees; 14 } 15 16 for (int i = start; i <= end; i++) 17 { 18 left_trees = BSTGenerate(start, i - 1); 19 right_trees = BSTGenerate(i + 1, end); 20 for (int j = 0; j < left_trees.size(); j++) 21 { 22 for (int k = 0; k < right_trees.size(); k++) 23 { 24 root = new TreeNode(i); 25 root->left = left_trees[j]; 26 root->right = right_trees[k]; 27 trees.push_back(root); 28 } 29 } 30 } 31 32 return trees; 33 }
leetcode 95. Unique Binary Search Trees II
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4296155.html