-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathBinaryTreeUpsideDown.java
More file actions
42 lines (41 loc) · 1.17 KB
/
BinaryTreeUpsideDown.java
File metadata and controls
42 lines (41 loc) · 1.17 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode upsideDownBinaryTree(TreeNode root) {
if (root == null || root.left == null) return root;
TreeNode newRoot = upsideDownBinaryTree(root.left);
root.left.right = root;
root.left.left = root.right;
root.left = null;
root.right = null;
return newRoot;
}
}
public class Solution {
public TreeNode upsideDownBinaryTree(TreeNode root) {
if (root == null || root.left == null) return root;
TreeNode newRoot = root.left;
TreeNode left = root.right;
TreeNode right = root;
root.left = null;
root.right = null;
while (newRoot != null) {
TreeNode nextRoot = newRoot.left;
TreeNode newLeft = newRoot.right;
newRoot.right = right;
newRoot.left = left;
left = newLeft;
right = newRoot;
if (nextRoot == null) break;
newRoot = nextRoot;
}
return newRoot;
}
}