1. 题目描述
给你 root1 和 root2 这两棵二叉搜索树。
请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。.
示例 1:
输入:root1 = [2,1,4], root2 = [1,0,3]
输出:[0,1,1,2,3,4]
示例 2:
输入:root1 = [0,-10,10], root2 = [5,1,7,0,2]
输出:[-10,0,0,1,2,5,7,10]
示例 3:
输入:root1 = [], root2 = [5,1,7,0,2]
输出:[0,1,2,5,7]
示例 4:
输入:root1 = [0,-10,10], root2 = []
输出:[-10,0,10]
示例 5:
输入:root1 = [1,null,8], root2 = [8,1]
输出:[1,1,8,8]
提示:
每棵树最多有 5000 个节点。
每个节点的值在 [-10^5, 10^5] 之间。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/all-elements-in-two-binary-search-trees
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.代码如下
#define deg_info(x) do {printf("---------- %s:%d: %s ----------\r\n",__FUNCTION__,__LINE__,x);}while(0);
typedef struct TreeNode Node;
int calcNodeNr(struct TreeNode *root)
{
if (root == NULL)
{
return 0;
}
return 1+calcNodeNr(root->left) + calcNodeNr(root->right);
}
//递归中序遍历
int traversInOrder(Node *root,int *pretArray,int *pindex)
{
if (root == NULL)
{
return 0;
}
traversInOrder(root->left,pretArray,pindex);
pretArray[*pindex] = root->val;
(*pindex) += 1;
traversInOrder(root->right,pretArray,pindex);
return 1;
}
//快速排序
int partition(int *g,int left,int right)
{
int key = g[left];
while(left<right)
{
while(left<right && g[right] >= key)
{
right--;
}
g[left] = g[right];
while(left<right && g[left] <= key)
{
left++;
}
g[right] = g[left];
}
g[left] = key;
return left;
}
void quicksort(int *g,int left,int right)
{
if(left < right)
{
int pivotloc = partition(g,left,right);
quicksort(g,left,pivotloc-1);
quicksort(g,pivotloc+1,right);
}
}
int* getAllElements(struct TreeNode* root1, struct TreeNode* root2, int* returnSize)
{
int *retArray = NULL;
int AllNum = 0;
Node *p1 = root1;
Node *p2 = root2;
int index = 0;
AllNum = calcNodeNr(root1) + calcNodeNr(root2);//计算出所有的节点个数
retArray = (int *)malloc(sizeof(int)*AllNum);
if (retArray == NULL)
{
deg_info("malloc failed!")
return NULL;
}
memset(retArray,0,sizeof(int)*AllNum);
traversInOrder(root1,retArray,&index);
traversInOrder(root2,retArray,&index);
if (index != AllNum)
{
deg_info("get an error order!")
return NULL;
}
//快速排序
quicksort(retArray,0,index-1);
*returnSize = index;
return retArray;
}