Leetcode 117. Populating Next Right Pointers in Each Node II
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Approach 1: Level Order Traversal
有三种BFS: PreOrder, InOrder, PostOrder、
BFS探索tree基于节点的level , level 是当前node距离root的长度。
Algorithm
- 初始化Queue,
(1) 像Queue添加pair(node.val, node.level), 可以继续添加(node.left.val,
node.level+1) 和 (node.right.val, node.level+1)
(2) 用NULL 分割,用Null作为一个level的结束标志。配合while loop 遍历queue。
while (!Q.empty())
{
size = Q.size()
for i in range 0..size
{
node = Q.pop()
Q.push(node.left)
Q.push(node.right)
}
}
- 添加(root, level == 0)
- pop(node,level)的同时, 添加(node.left, level+1) 和(node.right, level+1),重复queue.size() 次。
time complexity: O(N) ; space complexity: O(N)
Approach 2: Using previously established next pointers
We only move on to the level N+1 when we are done establishing the next pointers for the level N.
Node prev, leftmost; // public variables
Algorithm
定义三个变量:
- leftmost: represents the corresponding variable on each level.
- curr: It starts off with leftmost and then follows the next pointers all the way to the very end.
- prev: This is the pointer to the leading node on the next level.
leftmost = root
while (leftmost != null)
{
curr = leftmost
prev = NULL
while (curr != null)
{
→ process left child
→ process right child
→ set leftmost for the next level
curr = curr.next
}
}
For example:
level N : 2 -> 3 -> 5 -> 8
level N+1: 4, null, null, 6, 12, null, null, 10
- curr = NULL, leftmost = node 2, prev = node 4
- curr = node 3, leftmost = node 4, prev = node 6 (4->6)
- curr = node 5, leftmost = node 4, prev = node 12 (4->6->12)
- curr = node 9, leftmost = node 4, prev = node 10 (4->6->12->10)