forked from yubinbai/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
75 lines (72 loc) · 2.04 KB
/
Solution.java
File metadata and controls
75 lines (72 loc) · 2.04 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class Solution {
TreeNode upsideDownBinaryTree(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode curr = root;
while (curr.left != null) {
stack.push(curr);
curr = curr.left;
}
TreeNode result = curr;
while (!stack.isEmpty()) {
TreeNode parent = stack.pop();
curr.right = parent;
curr.left = parent.right;
parent.left = parent.right = null;
curr = parent;
}
return result;
}
TreeNode upsideDownBinaryTree2(TreeNode root) {
TreeNode prev = root, curr = root.left, newRoot = new TreeNode(0);
// reverse linked list on left subtree
while (curr != null) {
prev.left = newRoot.left;
newRoot.left = prev;
prev = curr;
curr = curr.left;
}
prev.left = newRoot.left;
newRoot.left = prev;
// rearrange left and right
curr = newRoot.left;
TreeNode swap;
while (curr != null) {
curr.right = curr.left;
swap = curr.left;
if (swap != null) {
curr.left = swap.right;
swap.right = null;
}
curr = swap;
}
return newRoot.left;
}
public static void inOrder(TreeNode e) {
if (e != null) {
inOrder(e.left);
System.out.format("%d ", e.val);
inOrder(e.right);
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.right = new TreeNode(3);
root.left = new TreeNode(2);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
inOrder(root);
System.out.println("");
Solution s = new Solution();
TreeNode ret = s.upsideDownBinaryTree(root);
inOrder(ret);
}
}