Skip to content

Commit 58bd9b1

Browse files
Added solution
1 parent 4387a3b commit 58bd9b1

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

populate_next_right_ptr.cpp

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
// Definition for a Node.
3+
class Node {
4+
public:
5+
int val;
6+
Node* left;
7+
Node* right;
8+
Node* next;
9+
10+
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
11+
12+
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
13+
14+
Node(int _val, Node* _left, Node* _right, Node* _next)
15+
: val(_val), left(_left), right(_right), next(_next) {}
16+
};
17+
*/
18+
class Solution {
19+
public:
20+
21+
Node* connect(Node* root) {
22+
if(root == NULL) return NULL;
23+
24+
if(root->left){ //check if child exists
25+
if(root->right) //check if immediate right node of child exists, if yes change the next ptr
26+
root->left->next = root->right;
27+
if(root->next) //check if neighbour of root exists for subtree, if yes, change the left subtree next ptr to right subtree
28+
root->right->next = root->next->left;
29+
}
30+
connect(root->left);
31+
connect(root->right);
32+
return root;
33+
}
34+
};

0 commit comments

Comments
 (0)