码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-01-06 18:14:12      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1599796

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!