forked from yubinbai/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
58 lines (56 loc) · 1.5 KB
/
Solution.java
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class Solution {
public void flatten(TreeNode root) {
_flatten(root);
}
public TreeNode[] _flatten(TreeNode e) {
TreeNode[] ret = new TreeNode[2];
if (e == null) {
ret[0] = ret[1] = null;
} else {
ret[0] = ret[1] = e;
TreeNode[] left = _flatten(e.left);
TreeNode[] right = _flatten(e.right);
e.left = null;
if (left[0] != null) {
e.right = left[0];
ret[1] = left[1];
}
if (right[0] != null) {
ret[1].right = right[0];
ret[1] = right[1];
}
}
return ret;
}
public void flattenSolution2(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root;
while (p != null || !stack.isEmpty()) {
if (p.right != null) {
stack.push(p.right);
}
if (p.left != null) {
p.right = p.left;
p.left = null;
} else if (!stack.isEmpty()) {
p.right = stack.pop();
}
p = p.right;
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.right = new TreeNode(2);
Solution s = new Solution();
s.flattenSolution2(root);
}
}