@shachopin/

# Binary Tree Upside Down

## No description

Files
• Main.java
• jdt.ls-java-project
Main.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
59
60
61
62
63
64
65
66
67
68
69
70
71
```
```class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}

MySolution on lintcode 649 Binary Tree Upside Down
/**
* Definition of TreeNode:
* public class TreeNode {
*     public int val;
*     public TreeNode left, right;
*     public TreeNode(int val) {
*         this.val = val;
*         this.left = this.right = null;
*     }
* }
*/

public class Solution {
/**
* @param root: the root of binary tree
* @return: new root
*/
public TreeNode upsideDownBinaryTree(TreeNode root) {
// write your code here
if (root == null) {
return null;
}
if (root.left == null) {
return root;
}
TreeNode newRoot = upsideDownBinaryTree(root.left); //每一层的newRoot其实都指向同一个reference
root.left.left = root.right;
root.left.right = root;
root.left = null;
root.right = null;
return newRoot;
}
}

==============================================

official solution:

// public class Solution {
//     /**
//      * @param root the root of binary tree
//      * @return the new root
//      */

//     TreeNode dfs(TreeNode cur) {
//         if (cur.left == null) {
//             return cur;
//         }
//         TreeNode newRoot = dfs(cur.left);
//         cur.left.right = cur;
//         cur.left.left = cur.right;
//         cur.left = null;            // important
//         cur.right = null;
//         return newRoot;
//     }

//     public TreeNode upsideDownBinaryTree(TreeNode root) {
//         // Write your code here
//         if (root == null) {
//             return null;
//         }
//         return dfs(root);
//     }
// }```