码迷,mamicode.com
首页 > 其他好文 > 详细

Unique Binary Search Trees II

时间:2015-11-11 16:15:52      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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.

题目:

这题要求将每个子树输出,思想就是对于n,以1-n为根节点,然后左右子树分别是比其小和比其大的节点构成的,对左右子树的的形态也要使用遍历,代码中使用的是foreach遍历:for(i:j)这种形式

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<TreeNode *> generateTrees(int n) {
13         if (n == 0) return generate(1, 0);
14         return generate(1, n);
15     }
16 private:
17     vector<TreeNode *> generate(int start, int end) {
18         vector<TreeNode*> subTree;
19         if (start > end) {
20             subTree.push_back(nullptr);
21             return subTree;
22         }
23         for (int k = start; k <= end; k++) {
24             vector<TreeNode*> leftSubs = generate(start, k - 1);
25             vector<TreeNode*> rightSubs = generate(k + 1, end);
26             for (auto i : leftSubs) {
27                 for (auto j : rightSubs) {
28                     TreeNode *node = new TreeNode(k);
29                     node->left = i;
30                     node->right = j;
31                     subTree.push_back(node);
32                 }
33             }
34         }
35         return subTree;
36     }
37 };

 

Unique Binary Search Trees II

标签:

原文地址:http://www.cnblogs.com/raichen/p/4956115.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!