《leetCode》:Populating Next Right Pointers in Each Node

来源:互联网 发布:sql 表 设计 编辑:程序博客网 时间:2024/05/29 17:42

题目

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.Note:You may only use constant extra space.You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).For example,Given the following perfect binary tree,         1       /  \      2    3     / \  / \    4  5  6  7After calling your function, the tree should look like:         1 -> NULL       /  \      2 -> 3 -> NULL     / \  / \    4->5->6->7 -> NULL

思路

思路,还是一样借助两个队列来进行完成,只要是关于按层来处理二叉树,一般就是借助两个队列来完成。

实现代码如下:

/** * 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;        }        Queue<TreeLinkNode> q1=new LinkedList<TreeLinkNode>();        Queue<TreeLinkNode> q2=new LinkedList<TreeLinkNode>();        q1.add(root);        root.next=null;        while(!(q1.isEmpty()&&q2.isEmpty())){            while(!q1.isEmpty()){                TreeLinkNode node=q1.poll();                if(node.left!=null){                    q2.add(node.left);                }                if(node.right!=null){                    q2.add(node.right);                }            }            while(!q2.isEmpty()){                TreeLinkNode node=q2.poll();                if(q2.isEmpty()){                    node.next=null;                }                else{                    node.next=q2.peek();                }                q1.add(node);                           }        }    }}

一次就AC了,哈哈哈哈

1 0
原创粉丝点击