3.3 Populating Next Right Pointers in Each Node II
Description
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
Method
Since it requires extra constant space, we use level-order to do it.
Time and Space Complexity
o(n) time o(1) space
Code
public class Solution {
public void connect(TreeLinkNode root) {
if (root == null){
return;
}
helper(root);
return;
}
public void helper(TreeLinkNode root){
if (root == null){
return;
}
if (root.left == null && root.right == null){
return;
}
TreeLinkNode node = root.next;
while (node != null){
if (node.left != null){
node = node.left;
break;
} else if (node.right != null){
node = node.right;
break;
}
node = node.next;
}
if (root.right != null){
if (root.left != null){
root.left.next = root.right;
}
root.right.next = node;
} else {
root.left.next = node;
}
helper(root.right);
helper(root.left);
}
} // o(1) space public void connect(TreeLinkNode root) { if (root == null){ return; } TreeLinkNode cur = root; TreeLinkNode head = null; TreeLinkNode pre = null;
while (cur != null){
while (cur != null){
if (cur.left != null){
if (pre != null){
pre.next = cur.left;
} else {
head = cur.left;
}
pre = cur.left;
}
if (cur.right != null){
if (pre != null){
pre.next = cur.right;
} else {
head = cur.right;
}
pre = cur.right;
}
cur = cur.next;
}
cur = head;
head = null;
pre = null;
}
}