网站网络结构设计,开发公司做管理公司天然气怎么做帐,最近三天的新闻大事国内,门户网站 集成 移动app 方案给你一个整数 n #xff0c;请你生成并返回所有由 n 个节点组成且节点值从 1 到 n 互不相同的不同 二叉搜索树 。可以按 任意顺序 返回答案。
思路一#xff1a;递归
struct TreeNode ** partition(int start, int end, int* returnSize){*returnSize 0;int size 32;stru…给你一个整数 n 请你生成并返回所有由 n 个节点组成且节点值从 1 到 n 互不相同的不同 二叉搜索树 。可以按 任意顺序 返回答案。
思路一递归
struct TreeNode ** partition(int start, int end, int* returnSize){*returnSize 0;int size 32;struct TreeNode** ans malloc(sizeof(struct TreeNode*) * size);if (start end) {ans[0] NULL;*returnSize 1;return ans;}for (int i start; i end; i) {int lsize, rsize;struct TreeNode** lnode partition(start, i, lsize);struct TreeNode** rnode partition(i 1, end, rsize);for (int m 0; m lsize; m) {for (int n 0; n rsize; n) {if (*returnSize size) {size 1;ans realloc(ans, sizeof(struct TreeNode*) * size);}int index (*returnSize);ans[index] malloc(sizeof(struct TreeNode));ans[index]-left lnode[m];ans[index]-right rnode[n];ans[index]-val i 1;}}free(lnode);free(rnode);}return ans;
}struct TreeNode** generateTrees(int n, int* returnSize){struct TreeNode** ans partition(0, n, returnSize);return ans;
}
分析
本题要列出所有二叉搜索树即可转换为列举左子树所有集合和右子树所有集合两个问题分别用递归函数将左右子树根节点存入最后输出即可解决
总结
本题考察二叉搜索树的枚举问题利用递归分别列举左右子树可解决