-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeUpsideDown_156.java
More file actions
48 lines (40 loc) · 1.18 KB
/
BinaryTreeUpsideDown_156.java
File metadata and controls
48 lines (40 loc) · 1.18 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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/**
* It only has left-only tree
*/
/*public class Solution {
TreeNode newroot = null;
public TreeNode UpsideDownBinaryTree(TreeNode root) {
if (root == null) return null;
if (root.left == null) return root;
TreeNode left = root.left;
newroot = UpsideDownBinaryTree(root.left);
left.left = root.right; left.right = root;
root.left = null; root.right = null; // XXXXXX you should reset the original
return newroot;
}
}*/
/**
* Without Recursion, top-down
*/
public class Solution{
public TreeNode UpsideDownBinaryTree(TreeNode root) {
if (root == null) return null;
TreeNode left = root.left, curr = root, oleft = curr.left, oright = curr.right;
while(left != null) {
oleft = left.left; left.left = oright;
oright = left.right; left.right = curr;
curr = left; left = oleft;
}
root.left = null; root.right = null;
return curr;
}
}