Skip to content

Commit cdf6b19

Browse files
Populating Next Right Pointers in Each Node II : Accepted
1 parent dcfd69c commit cdf6b19

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@ My accepted leetcode solutions to some of the common interview problems.
200200
- [Construct String From Binary Tree](problems/src/tree/ConstructStringFromBinaryTree.java) (Easy)
201201
- [Flatten Binary Tree to Linked List](problems/src/tree/FlattenBinaryTree.java) (Medium)
202202
- [Populating Next Right Pointers in Each Node](problems/src/tree/NextRightPointer.java) (Medium)
203+
- [Populating Next Right Pointers in Each Node II](problems/src/tree/NextRightPointerII.java) (Medium)
203204
- [Subtree of Another Tree](problems/src/tree/SubtreeOfAnotherTree.java) (Easy)
204205
- [Binary Tree Zigzag Level Order Traversal](problems/src/tree/ZigZagTraversal.java) (Medium)
205206
- [Binary Tree Inorder Traversal](problems/src/tree/BinaryTreeInorderTraversal.java) (Medium)
+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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

Comments
 (0)