-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_114.java
More file actions
44 lines (38 loc) · 1.09 KB
/
Copy pathP_114.java
File metadata and controls
44 lines (38 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package leetcode.medium;
import java.util.Deque;
import java.util.LinkedList;
import utils.DataStructures.TreeNode;
public class P_114 {
public void flatten(TreeNode root) {
helper(root, null);
}
private static TreeNode helper(TreeNode root, TreeNode prev) {
if (root == null) {
return prev;
}
prev = helper(root.right, prev);
prev = helper(root.left, prev);
root.right = prev;
root.left = null;
return root;
}
public void flattenIterative(TreeNode root) {
final Deque<TreeNode> stack = new LinkedList<>();
if (root != null) {
stack.addFirst(root);
}
while (!stack.isEmpty()) {
final TreeNode curr = stack.removeFirst();
if (curr.right != null) {
stack.addFirst(curr.right);
}
if (curr.left != null) {
stack.addFirst(curr.left);
}
if (!stack.isEmpty()) {
curr.right = stack.peekFirst();
}
curr.left = null;
}
}
}