当前位置: 代码迷 >> 综合 >> Leetcode 1305. 两棵二叉搜索树中的所有元素(DAY 7)
  详细解决方案

Leetcode 1305. 两棵二叉搜索树中的所有元素(DAY 7)

热度:71   发布时间:2023-11-17 20:39:22.0

原题题目

在这里插入图片描述



代码实现(首刷自解)

/*** 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().*/#define MAX 10010void visit(struct TreeNode* root,int *size,int* arr)
{
    if(root){
    visit(root->left,size,arr);arr[(*size)++] = root->val;visit(root->right,size,arr);}
}int* getAllElements(struct TreeNode* root1, struct TreeNode* root2, int* returnSize){
    int arr1[MAX/2],arr2[MAX/2],*arr;arr = (int*)malloc(sizeof(int) * MAX);(*returnSize) = 0;int size1 = 0,size2 = 0,pos1 = 0,pos2 = 0;visit(root1,&size1,arr1);visit(root2,&size2,arr2);while(pos1 < size1 && pos2 < size2){
    if(arr1[pos1] <= arr2[pos2])arr[(*returnSize)++] = arr1[pos1++];elsearr[(*returnSize)++] = arr2[pos2++];}while(pos1 < size1)arr[(*returnSize)++] = arr1[pos1++];while(pos2 < size2)arr[(*returnSize)++] = arr2[pos2++];return arr;
}