码迷,mamicode.com
首页 > 其他好文 > 详细

117. Populating Next Right Pointers in Each Node II

时间:2016-04-03 16:02:02      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

/**
 * 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) {
        //依然采用深度优先的思想
        Queue<TreeLinkNode> q=new LinkedList<TreeLinkNode>();
        if(root==null)
            return ;
        q.offer(root);
        int size=q.size();
        int count=0;
        TreeLinkNode temp=null;
        TreeLinkNode tail=null;
        while(!q.isEmpty())
        {

            temp=q.poll();
            if(temp.left!=null)
                q.offer(temp.left);
            if(temp.right!=null)
                q.offer(temp.right);
            if(count!=0)
            {
                tail.next=temp;
            }
            count++;
            if(count==size)
            {
                temp.next=null;
                count=0;
                size=q.size();
            }
            tail=temp;
        }
    }
}

 

117. Populating Next Right Pointers in Each Node II

标签:

原文地址:http://www.cnblogs.com/aguai1992/p/5349848.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!