-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay 8 Merge two binary tree.cpp
50 lines (43 loc) · 1.35 KB
/
Day 8 Merge two binary tree.cpp
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
// Merge two binary tree.CPP -
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
TreeNode *node = nullptr;
if (t1 != nullptr || t2 != nullptr) {
node = new TreeNode((t1 != nullptr ? t1->val : 0) + (t2 != nullptr ? t2->val : 0));
node->left = mergeTrees(t1 != nullptr ? t1->left : nullptr, t2 != nullptr ? t2->left : nullptr);
node->right = mergeTrees(t1 != nullptr ? t1->right : nullptr, t2 != nullptr ? t2->right : nullptr);
}
return node;
}
};
// Populating Next Right Pointer in each Node.cpp- leetcode solution
class Solution {
public:
Node* connect(Node* root) {
if(root==nullptr){
return root;
}
queue<Node*> q;
q.push(root);
while(!q.empty()){
int sz = q.size();
Node* prev = nullptr;
while(sz--){
Node* curr = q.front();
q.pop();
if(prev!=nullptr){
prev->next = curr;
}
prev = curr;
if(curr->left!=nullptr){
q.push(curr->left);
}
if(curr->right!=nullptr){
q.push(curr->right);
}
}
}
return root;
}
};