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

LeetCode#116 Populating Next Right Pointers in Each Node

时间:2015-09-10 22:28:50      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

?

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.

解决方案:

publicclass Solution {publicvoid connect(TreeLinkNode root) {
        if(root==null) return;
        Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
        queue.add(root);
        TreeLinkNode current;
        while(!queue.isEmpty()){
            current=queue.remove();
            if(current.left==null && current.right==null)   continue;
//下面解决非叶子节点的next指针问题
if(current.left!=null && current.right!=null) current.left.next = current.right; if(current.next!=null){ if(current.right==null) current.left.next = current.next.left!=null?current.next.left:current.next.right; else current.right.next = current.next.left!=null?current.next.left:current.next.right; }
//将下一层节点放入队列
if(current.left!=null) queue.add(current.left); if(current.right!=null) queue.add(current.right); } } }

LeetCode#116 Populating Next Right Pointers in Each Node

标签:

原文地址:http://www.cnblogs.com/kevinCK/p/4799191.html

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