给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
提示:
你只能使用常量级额外空间。
使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
思路:
使用递归,因为为满二叉树每次将节点左孩子next指向右孩子节点,在处理右孩子节点时候next可能指向null可能指向兄弟节点的左孩子节点,这里需要判断一下节点的兄弟节点是否存在(即node.next 是否存在),则可对右孩子next进行指定。
递归进行
class Solution {
public Node connect(Node root) {
if(root == null) return null;
if(root.left != null){
root.left.next = root.right;
}
if(root.right != null){
root.right.next = root.next != null ? root.next.left : null; //root.next存在则让root 右孩子next 指向 root.next的左孩子节点
}
connect(root.left);
connect(root.right);
return root;
}
}
使用队列,不符合题意。
思路:利用层次遍历,一层层的将孩子节点连接起来。
class Solution {
public Node connect(Node root) {
if(root == null) return null;
Queue<Node> queue = new LinkedList<Node>();
root.next = null;
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();//队列里面保存为一层的节点数。
while(size > 0){
// 将这一层孩子节点连接
Node temp = queue.poll();
if(temp.left != null){
temp.left.next = temp.right;
queue.offer(temp.left);
}
if(temp.right != null){
if(temp.next != null){ //右孩子节点与兄弟节点左孩子节点链接
temp.right.next = temp.next.left;
}else{
temp.right.next = null;
}
queue.offer(temp.right);
}
size --;
}
}
return root;
}
}