首页 > 代码库 > [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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。