|
| 1 | +/* |
| 2 | + You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: |
| 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 | + Initially, all next pointers are set to NULL. |
| 13 | +
|
| 14 | + Ex. Input: root = [1,2,3,4,5,6,7] |
| 15 | + Output: [1,#,2,3,#,4,5,6,7,#] |
| 16 | + Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, |
| 17 | + 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. |
| 18 | +
|
| 19 | + Time : O(N) |
| 20 | + Space : O(N) |
| 21 | +*/ |
| 22 | + |
| 23 | +/* |
| 24 | +// Definition for a Node. |
| 25 | +class Node { |
| 26 | +public: |
| 27 | + int val; |
| 28 | + Node* left; |
| 29 | + Node* right; |
| 30 | + Node* next; |
| 31 | +
|
| 32 | + Node() : val(0), left(NULL), right(NULL), next(NULL) {} |
| 33 | +
|
| 34 | + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} |
| 35 | +
|
| 36 | + Node(int _val, Node* _left, Node* _right, Node* _next) |
| 37 | + : val(_val), left(_left), right(_right), next(_next) {} |
| 38 | +}; |
| 39 | +*/ |
| 40 | + |
| 41 | +class Solution { |
| 42 | +public: |
| 43 | + Node* connect(Node* root) { |
| 44 | + if(root == NULL || (root -> right == NULL && root -> left == NULL)) |
| 45 | + return root; |
| 46 | + queue <Node*>q; |
| 47 | + q.push(root); |
| 48 | + |
| 49 | + while(!q.empty()) { |
| 50 | + int size = q.size(); |
| 51 | + Node* temp = NULL; |
| 52 | + |
| 53 | + for(int i = 0 ; i < size ; i++) { |
| 54 | + Node* front = q.front(); |
| 55 | + |
| 56 | + if(temp != NULL) |
| 57 | + temp -> next = front; |
| 58 | + temp = front; |
| 59 | + |
| 60 | + if(front -> left) { |
| 61 | + q.push(front -> left); |
| 62 | + q.push(front -> right); |
| 63 | + } |
| 64 | + q.pop(); |
| 65 | + } |
| 66 | + } |
| 67 | + return root; |
| 68 | + } |
| 69 | +}; |
0 commit comments