Populating Next Right Pointers in Each Node II
问题:
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
- You may only use constant extra space.
For example,
Given the following binary tree,
1 / \ 2 3 / \ \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
解决:
① 与Ⅰ不同的是二叉树不一定是完全二叉树。在判断下一个是否为空时还要判断父节点的下一节点的子节点的情况。递归遍历。
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {//1ms
public void connect(TreeLinkNode root) {
if(root == null) return;
TreeLinkNode rootNext = root.next;
TreeLinkNode next = null;
// rootNext如果是null说明已经处理完这一层的所有node
// next不等于null说明找到了找到最左边的下一个被连接的对象
while(rootNext != null && next == null){
if(rootNext.left != null){// 优先找左边
next = rootNext.left;
}else{
next = rootNext.right;
}
rootNext = rootNext.next;
}
if(root.left != null){
if(root.right != null){// 内部相连
root.left.next = root.right;
}else{ // 跨树相连
root.left.next = next;
}
}
if(root.right != null){ // 跨树相连
root.right.next = next;
}
connect(root.right);// 要先让右边都先连起来
connect(root.left);
}
}
② 非递归方法。与I相同,不需要改变。
public class Solution { //4ms
public void connect(TreeLinkNode root) {
if(root == null) return;
Queue<TreeLinkNode> queue = new LinkedList<>();
queue.offer(root);
while(! queue.isEmpty()){
int count = queue.size();
for (int i = 0;i < count ;i ++ ) {
TreeLinkNode cur = queue.poll();
if(i < count - 1){
cur.next = queue.peek();
}
if(cur.left != null) queue.offer(cur.left);
if(cur.right != null) queue.offer(cur.right);
}
}
}
}
③ 空间复杂度为O(1)的方法。首先定义了一个变量,用来指向每一层最左边的一个节点,由于左子结点可能缺失,所以这个最左边的节点有可能是上一层某个节点的右子结点,我们每往下推一层时,还要有个指针指向上一层的父节点,因为由于右子节点的可能缺失,所以上一层的父节点必须向右移,直到移到有子节点的父节点为止,然后把next指针连上,然后当前层的指针cur继续向右偏移,直到连完当前层所有的子节点,再向下一层推进,以此类推可以连上所有的next指针。
class Solution{ //1ms
public void connect(TreeLinkNode root) {
if(root == null) return;
TreeLinkNode lastHead = root;//指向上一层的头节点
TreeLinkNode lastCurrent = null;//上一层的指针
TreeLinkNode currentHead = null;//当前层的头节点
TreeLinkNode current = null;//当前层的指针
while(lastHead != null){
lastCurrent = lastHead;
while(lastCurrent != null){
//左子节点不为空
if(lastCurrent.left!=null) {
if(currentHead == null){
currentHead = lastCurrent.left;
current = lastCurrent.left;
}else{
current.next = lastCurrent.left;
current = current.next;
}
}
//右子节点不为空
if(lastCurrent.right != null){
if(currentHead == null){
currentHead = lastCurrent.right;
current = lastCurrent.right;
}else{
current.next = lastCurrent.right;
current = current.next;
}
}
lastCurrent = lastCurrent.next;
}
//更新头节点
lastHead = currentHead;
currentHead = null;
}
}
}