LeetCode[117] Population Next Right Pointers in Each Node II

     1
   /  \
  2    3
 / \    \
4   5    7



After calling your function, the tree should look like:
     1 -> NULL
   /  \
  2 -> 3 -> NULL
 / \    \
4-> 5 -> 7 -> NULL

Iteration

复杂度
O(N),O(1)

思路
设置一个dummy node 指向下一层要遍历的节点的开头的位置。

代码

public void connect(TreeLinkNode root) {
    TreeLinkNode dummy = new TreeLinkNode(0);
    TreeLinkNode pre = dummy;
    while(root != null) {
        if(root.left != null) {
            pre.next = root.left;
            pre = pre.next;
        }
        if(root.right != null) {
            pre.next = root.right;
            pre = pre.next;
        }
        root = root.next;
        // done with the search of current level
        if(root == null) {
            root = dummy.next;
            pre = dummy;
            dummy.next = null;
        }
    }

}

hellolittleJ17
10 声望11 粉丝