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
.
Example 1:
Input: root = [1,2,3,4,5,null,7] Output: [1,#,2,3,#,4,5,7,#] Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, 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.
Example 2:
Input: root = [] Output: []
Constraints:
- The number of nodes in the tree is in the range
[0, 6000]
. -100 <= Node.val <= 100
Follow-up:
- You may only use constant extra space.
- The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
Solution -2: Group nodes into levels
Use pre-order traversal to group nodes by levels.
Connects nodes in each level.
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua class Solution { public: Node* connect(Node* root) { vector<vector<Node*>> levels; dfs(root, 0, levels); for (auto& nodes : levels) for(int i = 0; i < nodes.size() - 1; ++i) nodes[i]->next = nodes[i+1]; return root; } private: void dfs(Node *root, int d, vector<vector<Node*>>& levels) { if (!root) return; if (levels.size() < d+1) levels.push_back({}); levels[d].push_back(root); dfs(root->left, d + 1, levels); dfs(root->right, d + 1, levels); } }; |
Solution -1: BFS level order traversal
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Author: Huahua class Solution { public: Node* connect(Node* root) { if (!root) return root; queue<Node*> q{{root}}; while (!q.empty()) { int size = q.size(); Node* p = nullptr; while (size--) { Node* t = q.front(); q.pop(); if (p) p->next = t, p = p->next; else p = t; if (t->left) q.push(t->left); if (t->right) q.push(t->right); } } return root; } }; |
Solution 1: BFS w/o extra space
Populating the next level while traversing current level.
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua class Solution { public: Node* connect(Node* root) { Node* p = root; while (p) { Node dummy; Node* c = &dummy; while (p) { if (p->left) c->next = p->left, c = c->next; if (p->right) c->next = p->right, c = c->next; p = p->next; } p = dummy.next; } return root; } }; |