116. Populating Next Right Pointers in Each Node

题目:

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

Initially, all next pointers are set to NULL.


  /*
    解题思路:如果该树为空,则直接返回;如果不为空,则通过队列进行层次遍历,设两个指针,一个last,刚开始时指向头结点,一个nlast指向遍历的最
    后一个节点,当last和刚出队列的值相等时,就把last的值更新为nlast,并且将刚队列的节点的next指针变为null;如果不等则不更新last指针,并且
    将刚出队列的节点的next指向队列的第一个节点
    */
    public void connect(TreeLinkNode root) {
        if(root==null){
            return;
        }
        LinkedList<TreeLinkNode> list=new LinkedList<TreeLinkNode>();
        TreeLinkNode last=root;
        TreeLinkNode nlast=null;
        list.add(root);
        while(list.size()!=0){
            TreeLinkNode temp=list.removeFirst();
            if(temp.left!=null){
                list.add(temp.left);
                nlast=temp.left;
            }
            if(temp.right!=null){
                list.add(temp.right);
                nlast=temp.right;
            }
            if(temp==last){//到改成的最后一个元素
                last=nlast;
                temp.next=null;
            }else{//如果不是的话,就指向他的兄弟
                temp.next=list.getFirst();
            }
        }//while
    }

猜你喜欢

转载自blog.csdn.net/zyilove34/article/details/74690868
今日推荐