/*
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


	- Reference - http://codeganker.blogspot.com/2014/04/populating-next-right-pointers-in-each.html

	- Keep track of current Head, last level head and current level rightmost node in processing

	- For processing one level
		1. Start from head of last level (leftmost node of last level)
		2. Keep track of head (leftmost node) of current level (first met node in processing current level)
		3. Using one pointer to store current rightmost node, and keep it linked to next right node found,
		   update the pointer
		4. Once current head is null (no node in current level), return

	- O(N) time, O(1) Space
*/

public class PopulatingNextRightPointersInEachNodeII {
	static class TreeLinkNode {
		int val;
		TreeLinkNode left, right, next;

		TreeLinkNode(int x) {
			val = x;
		}
	}

	public void connect(TreeLinkNode root) {
		if (root == null)
			return;
		TreeLinkNode lastHead = root;
		TreeLinkNode curHead = null;
		TreeLinkNode prev = null;
		while (lastHead != null) {
			TreeLinkNode lastLevelCur = lastHead;
			while (lastLevelCur != null) {
				if (lastLevelCur.left != null) {
					if (curHead == null) {
						curHead = lastLevelCur.left;
						prev = curHead;
					} else {
						prev.next = lastLevelCur.left;
						prev = prev.next;
					}
				}
				if (lastLevelCur.right != null) {
					if (curHead == null) {
						curHead = lastLevelCur.right;
						prev = curHead;
					} else {
						prev.next = lastLevelCur.right;
						prev = prev.next;
					}
				}
				lastLevelCur = lastLevelCur.next;
			}
			lastHead = curHead;
			curHead = null;
		}
	}
}
