首页 > 代码库 > [LeetCode]117 Populating Next Right Pointers in Each Node II

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

https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/

http://blog.csdn.net/linhuanmars/article/details/23510601

/**
 * 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) {
        
        // Same as https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/
        // But queue is not allowed
        
        TreeLinkNode curhead = root;
        TreeLinkNode nexthead = null;
        TreeLinkNode pre = null; // pre in next level
        
        // Iterate cur level, assign next level
        while (curhead != null)
        {
            // Start to iterate current level
            TreeLinkNode cur = curhead;
            while (cur != null)
            {
                if (cur.left != null)
                {
                    if (nexthead == null)
                        nexthead = cur.left;
                    if (pre != null)
                        pre.next = cur.left;
                    pre = cur.left;
                }
                
                if (cur.right != null)
                {
                    // Same logic as leftnode handling.
                    if (nexthead == null)
                        nexthead = cur.right;
                    if (pre != null)
                        pre.next = cur.right;
                    pre = cur.right;
                }
                cur = cur.next;
            }
            
            // After iteration this level.
            // Move to next nevel.
            if (nexthead != null)
            {
                curhead = nexthead;
                nexthead = null;
                pre = null;
            }
            else
            {
                // No next head.
                // We are finished.
                curhead = null;
            }
        }
    }
}


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