Skip to content

Commit 8bb0701

Browse files
authored
Update All Elements in Two Binary Search Trees.cpp
1 parent fae6d4b commit 8bb0701

File tree

1 file changed

+35
-13
lines changed

1 file changed

+35
-13
lines changed

All Elements in Two Binary Search Trees.cpp

Lines changed: 35 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,42 @@
1111
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
1212
* };
1313
*/
14+
1415
class Solution {
1516
public:
16-
vector<int> ans;
17-
void trav(TreeNode* root){
18-
if(root==NULL) return;
19-
ans.push_back(root->val);
20-
trav(root->left);
21-
trav(root->right);
22-
return;
23-
}
17+
18+
void pushelements(TreeNode*root,vector<int>&v){
19+
if(root==nullptr){
20+
return;
21+
}
22+
v.push_back(root->val);
23+
pushelements(root->left,v);
24+
pushelements(root->right,v);
25+
}
26+
2427
vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
25-
trav(root1);
26-
trav(root2);
27-
sort(ans.begin(), ans.end());
28-
return ans;
28+
if(root1==nullptr&root2==nullptr){
29+
vector<int>v;
30+
return v;
31+
}
32+
else if(root1==nullptr){
33+
vector<int>v;
34+
pushelements(root2,v);
35+
sort(v.begin(),v.end());
36+
return v;
37+
}
38+
else if(root2==nullptr){
39+
vector<int>v;
40+
pushelements(root1,v);
41+
sort(v.begin(),v.end());
42+
return v;
43+
}
44+
else{
45+
vector<int>v;
46+
pushelements(root1,v);
47+
pushelements(root2,v);
48+
sort(v.begin(),v.end());
49+
return v;
50+
}
2951
}
30-
};
52+
};

0 commit comments

Comments
 (0)