leetcode: Populating Next Right Pointers in Each Node II

来源:互联网 发布:淘宝双十一2017销售额 编辑:程序博客网 时间:2024/06/05 01:51

和1的区别在于不是完全的二叉树,因而会出现左右节点的各种分布情况。   这里还是利用while来找到每个节点的next节点,由于这个过程中我们需要知道每个节点父节点的next节点,因而在遍历的过程中一定要按照先右子结点,再左子结点的顺序!!! 这样可以保证遍历过程中每个节点的父节点的next信息都已得到。


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


0 0
原创粉丝点击