-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnect Nodes at Same Level.cpp
78 lines (68 loc) · 2.09 KB
/
Connect Nodes at Same Level.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
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
// Connect Nodes at Same Level
// Difficulty: MediumAccuracy: 55.78%Submissions: 96K+Points: 4
// Given a binary tree, connect the nodes that are at same level. You'll be given an addition nextRight pointer for the same.
// Initially, all the nextRight pointers point to garbage values. Your function should set these pointers to point next right for each node.
// 10 10 ------> NULL
// / \ / \
// 3 5 => 3 ------> 5 --------> NULL
// / \ \ / \ \
// 4 1 2 4 --> 1 -----> 2 -------> NULL
// Example 1:
// Input:
// 3
// / \
// 1 2
// Output:
// 3 1 2
// 1 3 2
// Explanation:The connected tree is
// 3 ------> NULL
// / \
// 1-----> 2 ------ NULL
// Example 2:
// Input:
// 10
// / \
// 20 30
// / \
// 40 60
// Output:
// 10 20 30 40 60
// 40 20 60 10 30
// Explanation:The connected tree is
// 10 ----------> NULL
// / \
// 20 ------> 30 -------> NULL
// / \
// 40 ----> 60 ----------> NULL
// Your Task:
// You don't have to take input. Complete the function connect() that takes root as parameter and connects the nodes at same level. The printing is done by the driver code. First line of the output will be level order traversal and second line will be inorder travsersal
// Expected Time Complexity: O(N).
// Expected Auxiliary Space: O(N).
// Constraints:
// 1 ≤ Number of nodes ≤ 105
// 0 ≤ Data of a node ≤ 105
class Solution
{
public:
void connect(Node *root){
if(!root)return;
queue<Node*>q;
q.push(root);
while(!q.empty()){
int size=q.size();
Node* prev=NULL;
while(size--){
Node* curr=q.front();
q.pop();
if(prev){
prev->nextRight=curr;
}
prev=curr;
if(curr->left)q.push(curr->left);
if(curr->right)q.push(curr->right);
}
prev->nextRight=NULL;
}
}
};