题目
给定一个二叉树
struct Node { int val; Node *left; Node *right; Node *next; }
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
解题思路
这题使用队列来解决思路比较清晰,把每一层的结点放入队列中,在每一层的后面放入一个null作为每一层的结束结点,每次都把每一层的前一个结点的next指向下一个即可。
代码如下
class Solution {
public Node connect(Node root) {
if(root == null) return null;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
queue.add(null);
while(!queue.isEmpty()) {
Node preNode = queue.remove();
Node nextNode = queue.peek();
preNode.next = nextNode;
if(preNode.left != null) queue.add(preNode.left);
if(preNode.right != null) queue.add(preNode.right);
if(nextNode == null) {
//每一层的结束
queue.remove();
if(!queue.isEmpty())
queue.add(null);
}
}
return root;
}
}
提交结果
成功
显示详情
执行用时 : 7 ms, 在Populating Next Right Pointers in Each Node II的Java提交中击败了51.00% 的用户
内存消耗 : 67.5 MB, 在Populating Next Right Pointers in Each Node II的Java提交中击败了5.12% 的用户