标签:gen ret 节点 ++ tree efi == bin public
题目:
给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。
示例:
输入: 3
输出:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
解释:
以上的输出对应以下 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
解法:
用DFS枚举,划分左右子树,递归构造。
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 *> generate(int beg, int end) 13 { 14 vector<TreeNode* > ret; 15 16 if (beg > end) 17 { 18 ret.push_back(NULL); 19 return ret; 20 } 21 22 for(int i = beg; i <= end; i++) 23 { 24 vector<TreeNode* > leftTree = generate(beg, i - 1); 25 vector<TreeNode* > rightTree = generate(i + 1, end); 26 27 for(int j = 0; j < leftTree.size(); j++) 28 { 29 for(int k = 0; k < rightTree.size(); k++) 30 { 31 TreeNode *node = new TreeNode(i); 32 ret.push_back(node); 33 node->left = leftTree[j]; 34 node->right = rightTree[k]; 35 } 36 } 37 } 38 return ret; 39 } 40 41 vector<TreeNode *> generateTrees(int n) 42 { 43 vector<TreeNode*> ret; 44 if (0 == n) 45 { 46 return ret; 47 } 48 49 ret = generate(1, n); 50 return ret; 51 } 52 };
标签:gen ret 节点 ++ tree efi == bin public
原文地址:https://www.cnblogs.com/ocpc/p/12817295.html