Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charlespunk/4702357 to your computer and use it in GitHub Desktop.
Save charlespunk/4702357 to your computer and use it in GitHub Desktop.
Populating Next Right Pointers in Each Node II Oct 28 '12
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 {
public void connect(TreeLinkNode root) {
// Start typing your Java solution below
// DO NOT write main() function
while(root != null){
TreeLinkNode thisNode = root;
while(thisNode != null){
if(thisNode.left != null && thisNode.right != null){
thisNode.left.next = thisNode.right;
thisNode.right.next = getNextLevelFirst(thisNode.next);
}
else if(thisNode.left != null || thisNode.right != null){
getNextLevelFirst(thisNode).next = getNextLevelFirst(thisNode.next);
}
thisNode = thisNode.next;
}
root = getNextLevelFirst(root);
}
}
public TreeLinkNode getNextLevelFirst(TreeLinkNode root){
if(root == null) return null;
else if(root.left != null) return root.left;
else if(root.right != null) return root.right;
else return getNextLevelFirst(root.next);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment