117. Populating Next Right Pointers in Each Node II
Given a binary tree
1 2 3 4 5 6
| struct Node { int val; Node *left; Node *right; Node *next; }
|
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.
Initially, all next pointers are set to NULL.
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
|
class Solution { vector<Node*> lvls; void travel(Node* node, int lvl) { if(!node) return; if(lvls[lvl]) { lvls[lvl]->next = node; } lvls[lvl] = node; travel(node->left, lvl+1); travel(node->right, lvl+1); } public: Node* connect(Node* root) { lvls = vector<Node*>(6001,NULL); travel(root, 0); return root; } };
|