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

时间:2022-02-08 21:43:03

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);
}

}
}