题目描述
题目难度:Medium
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *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.
Example:

Note:
You may only use constant extra space.
Recursive approach is fine, implicit stack space does not count as extra space for this problem.
AC代码1
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val,Node _left,Node _right,Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public Node connect(Node root) {
if(root == null) return root;
Queue<Node> queue = new LinkedList<Node>();
queue.offer(root);
Node pre = null;
Node cur = null;
while(!queue.isEmpty()){
int size = queue.size();
pre = queue.poll();
if(pre.left != null) queue.offer(pre.left);
if(pre.right != null) queue.offer(pre.right);
for(int i = 0;i < size - 1;i++){
cur = queue.poll();
pre.next = cur;
pre = cur;
if(pre.left != null) queue.offer(pre.left);
if(pre.right != null) queue.offer(pre.right);
}
}
return root;
}
}
AC代码2
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val,Node _left,Node _right,Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public Node connect(Node root) {
if(root == null) return root;
Node startNode = root;
while(startNode != null){
Node cur = startNode;
startNode = cur.left;
while(cur != null){
if(cur.left != null) cur.left.next = cur.right;
if(cur.right != null) cur.right.next = (cur.next == null) ? null : cur.next.left;
cur = cur.next;
}
}
return root;
}
}
本文介绍了一种解决完美二叉树中填充Next指针的问题的方法,旨在让每个节点的Next指针指向其右侧相邻的节点。提供两种解决方案,一种使用队列进行层次遍历,另一种通过连接相邻节点实现。
282

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



