[LeetCode]Populating Next Right Pointers in Each Node II
public class Solution { public void connect(TreeLinkNode root) { if (root == null) { return; } TreeLinkNode pre = root; TreeLinkNode next = find_next(pre); while (next != null) { TreeLinkNode tmp = next; while (pre != null) { if (tmp == pre.left) { if (pre.right != null) { tmp.next = pre.right; tmp = tmp.next; pre = pre.next; } else { pre = pre.next; } } else { if (pre.left != null) { tmp.next = pre.left; tmp = tmp.next; } else if (pre.right != null && tmp != pre.right) { tmp.next = pre.right; pre = pre.next; tmp = tmp.next; } else { pre = pre.next; } } } pre = next; next = find_next(next); } } public TreeLinkNode find_next (TreeLinkNode pre) { if (pre.left != null) { return pre.left; } else if (pre.right != null) { return pre.right; } else if (pre.next != null) { return find_next(pre.next); } else { return null; } } }