题目:
给你 root1 和 root2 这两棵二叉搜索树。请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。.
示例 1:
输入:root1 = [2,1,4], root2 = [1,0,3]
输出:[0,1,1,2,3,4]
示例 2:
输入:root1 = [1,null,8], root2 = [8,1]
输出:[1,1,8,8]
提示:
每棵树的节点数在 [0, 5000] 范围内
-105 <= Node.val <= 105
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/all-elements-in-two-binary-search-trees
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
结果:
解题思路:
我这个方法就是很暴力的解决。没有什么技术难度的。
首先将两棵树中所有节点的值取出。
然后对其进行排序输出。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
void GetValues(int *temp, struct TreeNode *root, int *returnSize)
{
if(root == NULL) {
return;
}
temp[*returnSize] = root->val;
*returnSize += 1;
if (root->left != NULL) {
GetValues(temp, root->left, returnSize);
}
if (root->right != NULL) {
GetValues(temp, root->right, returnSize);
}
return;
}
int compare(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
int* getAllElements(struct TreeNode* root1, struct TreeNode* root2, int* returnSize){
int *retArr = (int *)malloc(sizeof(int) * 10000);
*returnSize = 0;
GetValues(retArr, root1, returnSize);
GetValues(retArr, root2, returnSize);
qsort(retArr, *returnSize, sizeof(int), compare);
return retArr;
}