Populating Next Right Pointers in Each Node II 任意(非完美)二叉树添加next指针 @LeetCode

来源:互联网 发布:linux 播放 4k 视频 编辑:程序博客网 时间:2024/06/06 03:35

http://blog.csdn.net/fightforyourdream/article/details/14514165

在上题基础上扩展,此时数不是完美二叉树,而是任意二叉树

这道题有些tricky,有时间回头再研究一下


package Level4;import Utility.TreeLinkNode;/** * Populating Next Right Pointers in Each Node II  *  *  Follow up for problem "Populating Next Right Pointers in Each Node".What if the given tree could be any binary tree? Would your previous solution still work?Note:You may only use constant extra space.For example,Given the following binary tree,         1       /  \      2    3     / \    \    4   5    7After calling your function, the tree should look like:         1 -> NULL       /  \      2 -> 3 -> NULL     / \    \    4-> 5 -> 7 -> NULLDiscuss * */public class S117 {public static void main(String[] args) {}public static void connect(TreeLinkNode root) {// 空节点就直接返回if (root == null){return;}// 找到与root同一行的next nodeTreeLinkNode rootNext = root.next;TreeLinkNode next = null;// 下一个被连接的对象// rootNext如果是null说明已经处理完这一层的所有node// next不等于null说明找到了找到最左边的下一个被连接的对象while (rootNext != null && next == null){if (rootNext.left != null){// 优先找左边next = rootNext.left;} else{next = rootNext.right;}rootNext = rootNext.next;} if (root.left != null){if (root.right != null){//内部相连root.left.next = root.right;}else{// 跨树相连root.left.next = next;}}if (root.right != null){// 跨树相连root.right.next = next;}connect(root.right);// 要先让右边都先连起来connect(root.left);    }}


第二次做修改了一个地方的bug(在找rootnext时增加了break,及时退出),居然提交两次就通过了。

果然做LeetCode的真谛在于:遇到不懂 => 查答案 => 自己理解写出来或背下来 => 过一段时间后第二遍重做

比如这道题,我印象最深刻的是一定要先处理右子树再处理左子树,知道这点就足够写出来了。

关键就是找到next节点是在哪里,而这又要求找到rootnext节点在哪里。那个while循环就是破题的关键。


/** * 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) {        if(root == null){            return;        }                TreeLinkNode rootnext = root.next;        TreeLinkNode next = null;        while(rootnext != null){            if(rootnext.left != null){                next = rootnext.left;                break;            }else if(rootnext.right != null){                next = rootnext.right;                break;            }else{                rootnext = rootnext.next;            }        }                if(root.right != null){            root.right.next = next;        }        if(root.left != null){            if(root.right != null){                root.left.next = root.right;            }else{                root.left.next = next;            }        }                connect(root.right);        connect(root.left);    }}