/** * 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) { if (root == null) { return; } TreeLinkNode mostLeft = root; while (mostLeft != null) { root = mostLeft; while(root != null) { if (root.left != null && root.right != null) { root.left.next = root.right; root.right.next = getNextNode(root.next); } else if (root.left != null || root.right != null) { getNextNode(root).next = getNextNode(root.next); } root = root.next; } mostLeft = getNextNode(mostLeft); } } private TreeLinkNode getNextNode(TreeLinkNode root) { if (root == null) { return null; } if (root.left != null) { return root.left; } if (root.right != null) { return root.right; } return getNextNode(root.next); }}