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
每次从nodeQueue中取出一个node,levelQueue中取出其层数。当:
1.nodeQueue没有下一个node
2.nodeQueue有下一个node,但下一个node的层数和现在的node的层数不一样
node.next=null。
剩下的情况就是node.next=nodeQueue中下一个元素。
<pre name="code" class="java">public class Solution {
public void connect(TreeLinkNode root) {
if(root == null)
return;
LinkedList<TreeLinkNode> nodeQueue = new LinkedList<TreeLinkNode>();
LinkedList<Integer> levelQueue = new LinkedList<Integer>();
nodeQueue.addLast(root);
levelQueue.add(0);
while(!nodeQueue.isEmpty()){
TreeLinkNode node = nodeQueue.pollFirst();
int level = levelQueue.pollFirst();
//if this is level 0
//or if there is no more node in the queue
//or the next node's level is not equal to the current node's level
//then node.next is null
if(level == 0){
node.next = null;
}
else if(nodeQueue.isEmpty()){
node.next = null;
}
else{
if(level != levelQueue.peekFirst())
node.next = null;
//otherwise, node.next equals the next node in the queue
else{
node.next = nodeQueue.peekFirst();
}
}
if(node.left != null){
nodeQueue.addLast(node.left);
levelQueue.addLast(level + 1);
}
if(node.right != null){
nodeQueue.addLast(node.right);
levelQueue.addLast(level + 1);
}
}
}
}
更新:
回头看这个问题发现要求有constant extra space,于是不能用queue了。不过还好这里每个node都有一个next pointer,可以利用next来进行层序遍历。
要点就是要记录下一层的起点node,以及前一个node的right child。
public class Solution {
public void connect(TreeLinkNode root) {
if(root == null)
return;
//this pointer holds the head of the next level
TreeLinkNode nextLineFirst = root;
//outer loop loops between levels
while(nextLineFirst != null){
TreeLinkNode current = nextLineFirst;
TreeLinkNode previousRight = null;
nextLineFirst = null;
//inner loop loops within in a level, between nodes
while(current != null){
if(nextLineFirst == null && current.left != null){
//update the next level head pointer
nextLineFirst = current.left;
}
if(current.left != null){
//current is not a leaf, link its left child to its right child
current.left.next = current.right;
}
if(previousRight != null){
//link the previous right child to the current node's left child
previousRight.next = current.left;
}
previousRight = current.right;
current = current.next;
}
}
}
}

本文介绍了一种在完美二叉树中填充每个节点的next指针的方法,使得每个节点指向其右侧相邻节点。文章提供了两种解决方案,一种使用额外的队列进行层序遍历,另一种使用常数额外空间通过next指针本身实现遍历。

被折叠的 条评论
为什么被折叠?



