-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy path_156.java
30 lines (28 loc) · 853 Bytes
/
_156.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
/**
* LeetCode 156 - Binary Tree Upside Down
* <p>
* This problem can be used via a single post-order traversal.
* But honestly speaking, I don't like the problem statement at all...
*/
public class _156 {
TreeNode r, newRoot;
private void dfs(TreeNode root, TreeNode parent) {
if (root == null) return;
dfs(root.left, root);
dfs(root.right, root);
if (r == null) {
r = new TreeNode(root.val);
newRoot = r;
} else if (parent != null && parent.right == root) r.left = new TreeNode(root.val);
else {
r.right = new TreeNode(root.val);
r = r.right;
}
}
public TreeNode upsideDownBinaryTree(TreeNode root) {
if (root == null) return null;
r = newRoot = null;
dfs(root, null);
return newRoot;
}
}