Description

LeetCode 117

Given a binary tree

}

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.

Note:

• You may only use constant extra space.
• Recursive approach is fine, implicit stack space does not count as extra space for this problem.

Example:

Given the following binary tree,

1
/  \
2    3
/ \    \
4   5    7

After calling your function, the tree should look like:

1 -> NULL
/  \
2 -> 3 -> NULL
/ \    \
4-> 5 -> 7 -> NULL

Analysis

The solution is very difficult to come up with. Maybe for data structure problems, we should try to find a good way to memory the solution.

The main idea is to traverse the tree by level. Just use the next pointer instead of using other tools. We need to store three pointers which are the node that is being visited, the node whose next pointer will be set, the node which is the first node of next level.

Solution

/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
*     int val;
*     TreeLinkNode left, right, next;
*     TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
TreeLinkNode pre = null;
TreeLinkNode cur = root;
while (cur != null) {
while (cur != null) {
if (cur.left != null) {
if (pre != null) {
pre.next = cur.left;
} else head = cur.left;
pre = cur.left;
}
if (cur.right != null) {
if (pre != null) {
pre.next = cur.right;
} else head = cur.right;
pre = cur.right;
}
cur = cur.next;
}