-
Notifications
You must be signed in to change notification settings - Fork 0
/
1305 All Elements in Two Binary Search Trees.c
78 lines (64 loc) · 1.67 KB
/
1305 All Elements in Two Binary Search Trees.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int count_nodes(struct TreeNode * root)
{
if(root == NULL)
return 0;
return (1+count_nodes(root->left)+count_nodes(root->right));
}
void inorder(struct TreeNode * root, int * ret_arr, int * ret_arr_index)
{
if(root==NULL)
return;
inorder(root->left, ret_arr, ret_arr_index);
ret_arr[(*ret_arr_index)++] = root->val;
inorder(root->right, ret_arr, ret_arr_index);
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* getAllElements(struct TreeNode* root1, struct TreeNode* root2, int* returnSize)
{
int nodes1 = count_nodes(root1);
int nodes2 = count_nodes(root2);
int * ret_arr = (int *)malloc(sizeof(int) * (nodes1 + nodes2));
int ret_arr_index = 0;
int * arr1 = (int *)malloc(sizeof(int) * nodes1);
int arr1_index = 0;
int * arr2 = (int *)malloc(sizeof(int) * nodes2);
int arr2_index = 0;
inorder(root1, arr1, &arr1_index);
inorder(root2, arr2, &arr2_index);
int i=0, j=0;
for(i=0,j=0; i<arr1_index && j<arr2_index; )
{
if(arr1[i] <=arr2[j])
{
ret_arr[ret_arr_index++] = arr1[i];
i++;
}
else
{
ret_arr[ret_arr_index++] = arr2[j];
j++;
}
}
while(i<arr1_index)
{
ret_arr[ret_arr_index++] = arr1[i];
i++;
}
while(j<arr2_index)
{
ret_arr[ret_arr_index++] = arr2[j];
j++;
}
*returnSize = ret_arr_index;
return ret_arr;
}