|
| 1 | +/* |
| 2 | + Given a binary tree |
| 3 | +
|
| 4 | + struct Node { |
| 5 | + int val; |
| 6 | + Node *left; |
| 7 | + Node *right; |
| 8 | + Node *next; |
| 9 | + } |
| 10 | + |
| 11 | + Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. |
| 12 | + |
| 13 | + Initially, all next pointers are set to NULL. |
| 14 | +
|
| 15 | + Ex. Input: root = [1,2,3,4,5,null,7] |
| 16 | + Output: [1,#,2,3,#,4,5,7,#] |
| 17 | + Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, |
| 18 | + just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. |
| 19 | +
|
| 20 | + Time : O(N) |
| 21 | + Space : O(1) |
| 22 | +*/ |
| 23 | + |
| 24 | +/* |
| 25 | +// Definition for a Node. |
| 26 | +class Node { |
| 27 | +public: |
| 28 | + int val; |
| 29 | + Node* left; |
| 30 | + Node* right; |
| 31 | + Node* next; |
| 32 | +
|
| 33 | + Node() : val(0), left(NULL), right(NULL), next(NULL) {} |
| 34 | +
|
| 35 | + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} |
| 36 | +
|
| 37 | + Node(int _val, Node* _left, Node* _right, Node* _next) |
| 38 | + : val(_val), left(_left), right(_right), next(_next) {} |
| 39 | +}; |
| 40 | +*/ |
| 41 | + |
| 42 | +class Solution { |
| 43 | +public: |
| 44 | + Node* connect(Node* root) { |
| 45 | + if(root == NULL) |
| 46 | + return NULL; |
| 47 | + Node* parent = root; |
| 48 | + |
| 49 | + while(parent) { |
| 50 | + Node* newNode = new Node; |
| 51 | + Node* temp = newNode; |
| 52 | + |
| 53 | + while(parent) { |
| 54 | + if(parent -> left) { |
| 55 | + temp -> next = parent -> left; |
| 56 | + temp = temp -> next; |
| 57 | + } |
| 58 | + if(parent -> right) { |
| 59 | + temp -> next = parent -> right; |
| 60 | + temp = temp -> next; |
| 61 | + } |
| 62 | + parent = parent -> next; |
| 63 | + } |
| 64 | + parent = newNode -> next; |
| 65 | + } |
| 66 | + return root; |
| 67 | + } |
| 68 | +}; |
0 commit comments