populating-next-right-pointers-in-each-node II

来源:互联网 发布:js input 光标颜色 编辑:程序博客网 时间:2024/06/14 11:21

I Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL.

Initially, all next pointers are set toNULL.

简单递归
/** * Created by a819 on 2017/8/8. */class TreeLinkNode {    int val;    TreeLinkNode left, right, next;    TreeLinkNode(int x) { val = x; }}public class Connect {    public void connect(TreeLinkNode root) {        if (root == null)            return;        else {            con(root);            // root.next=null;        }    }    public void con(TreeLinkNode root){        if (root.left != null && root.right != null) {            root.left.next = root.right;            if (root.next!=null)                root.right.next=root.next.left;            connect(root.left);            connect(root.right);        }        else return;    }}

II 循环遍历(可能不是完全二叉树)

/** * 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 lastnode=root;//每一行的头结点        TreeLinkNode curhead=null;//定义当前行的头结点        TreeLinkNode prenode=null;//定义当前行向后遍历的节点        while(lastnode!=null)        {            TreeLinkNode nextnode=lastnode; //定义当前行的遍历节点            while(nextnode!=null)            {                if(nextnode.left!=null)  //说明有左孩子节点                {                    //判断当前有没有头结点,即该节点是不是下一行第一个节点                    if(curhead==null) //没有头结点                    {                        curhead=nextnode.left;                        prenode=curhead;                    }else{ //有头结点,prenode向后前进                        prenode.next=nextnode.left;                        prenode=prenode.next;                    }                }                if(nextnode.right!=null) //说明有右孩子节点                {                    //同样需要判断当前有没有头结点                    if(curhead==null) //没有头结点                    {                        curhead=nextnode.right;                        prenode=curhead;                    }else{ //有头结点,prenode向后前进                        prenode.next=nextnode.right;                        prenode=prenode.next;                    }                }                nextnode=nextnode.next;            }            //当前行结束,进入下一行            lastnode=curhead;            curhead=null;   //需要置为null,因为是新的一层需要建立        }     }}
II 思想转自http://www.programcreek.com/2014/05/leetcode-populating-next-right-pointers-in-each-node-java/



阅读全文
0 0