Leetcode 116. Populating Next Right Pointers in Each Node 链接邻居 解题报告

1 解题思想

这道题是给了一个二叉树,但是这个二叉树是传统的二叉树,也就是说一个节点只有左右子节点
任务是要求链接每一个节点的右邻居,具体示意可以看原题。

解题方法就是传统的不能再传统的BFS了,具体一点就是BFS的过程,记录层数信息,然后保存前一个节点,遍历到当前节点的话,让前一个结点的next链接到当前节点(当然是合法的连接了,要是前面没有节点或者当前节点是最后一个就特殊处理了)

2 原题

116. Populating Next Right Pointers in Each Node  
Question
Editorial Solution 
My Submissions 

Total Accepted: 103748
Total Submissions: 282297
Difficulty: Medium

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  7

After calling your function, the tree should look like:
         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NULL

3 AC解

/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */

 /**
  * 因为这个是满二叉树,所以BFS遍历+一个计数器就可以了
  * 要是计数显示还在同一层,那么就去队列的下一个就可以,不然就是为空
  */
public class Solution {
    public void connect(TreeLinkNode root) {
        Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
        if(root!=null)
             queue.add(root);
        int count=1,gate=2;
        while(queue.isEmpty()==false){
            TreeLinkNode tmp=queue.poll();
            if(++count==gate){
                gate*=2;
                tmp.next=null;
            }
            else {
                tmp.next=queue.peek();
            }
            if(tmp.left!=null) queue.add(tmp.left);
            if(tmp.right!=null) queue.add(tmp.right);
        }

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值