|
| 1 | +package tree; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by gouthamvidyapradhan on 03/10/2017. |
| 5 | + * <p> |
| 6 | + * Follow up for problem "Populating Next Right Pointers in Each Node". |
| 7 | + * <p> |
| 8 | + * What if the given tree could be any binary tree? Would your previous solution still work? |
| 9 | + * <p> |
| 10 | + * Note: |
| 11 | + * <p> |
| 12 | + * You may only use constant extra space. |
| 13 | + * For example, |
| 14 | + * Given the following binary tree, |
| 15 | + * 1 |
| 16 | + * / \ |
| 17 | + * 2 3 |
| 18 | + * / \ \ |
| 19 | + * 4 5 7 |
| 20 | + * After calling your function, the tree should look like: |
| 21 | + * 1 -> NULL |
| 22 | + * / \ |
| 23 | + * 2 -> 3 -> NULL |
| 24 | + * / \ \ |
| 25 | + * 4-> 5 -> 7 -> NULL |
| 26 | + */ |
| 27 | +public class NextRightPointerII { |
| 28 | + |
| 29 | + public static void main(String[] args) throws Exception { |
| 30 | + TreeLinkNode root = new TreeLinkNode(1); |
| 31 | + root.left = new TreeLinkNode(2); |
| 32 | + root.right = new TreeLinkNode(3); |
| 33 | + root.right.right = new TreeLinkNode(4); |
| 34 | + root.right.right.left = new TreeLinkNode(5); |
| 35 | + root.right.right.right = new TreeLinkNode(6); |
| 36 | + new NextRightPointerII().connect(root); |
| 37 | + } |
| 38 | + |
| 39 | + public void connect(TreeLinkNode root) { |
| 40 | + TreeLinkNode prev = new TreeLinkNode(0); |
| 41 | + TreeLinkNode first = null; |
| 42 | + while (root != null) { |
| 43 | + if (root.left != null) { |
| 44 | + prev.next = root.left; |
| 45 | + prev = root.left; |
| 46 | + if (first == null) { |
| 47 | + first = root.left; |
| 48 | + } |
| 49 | + } |
| 50 | + if (root.right != null) { |
| 51 | + prev.next = root.right; |
| 52 | + prev = root.right; |
| 53 | + if (first == null) { |
| 54 | + first = root.right; |
| 55 | + } |
| 56 | + } |
| 57 | + root = root.next; |
| 58 | + if (root == null) { |
| 59 | + root = first; |
| 60 | + first = null; |
| 61 | + prev = new TreeLinkNode(0); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + public static class TreeLinkNode { |
| 67 | + int val; |
| 68 | + TreeLinkNode left, right, next; |
| 69 | + |
| 70 | + TreeLinkNode(int x) { |
| 71 | + val = x; |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments