-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvertBinaryTree.java
More file actions
67 lines (64 loc) · 1.42 KB
/
InvertBinaryTree.java
File metadata and controls
67 lines (64 loc) · 1.42 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
package easy;
import util.TreeNode;
/**
*
* ClassName: InvertBinaryTree
* @author chenyiAlone
* Create Time: 2019/02/27 16:39:04
* Description: No.226
*
*
* ----------- update -----------------
* 思路:
* 简化了原来的题解,其实过程完全一样,只是刚刚发现完全可以不依靠额外的方法,在原方法的基础上递归即可
*
*
*
* Invert a binary tree.
*
* Example:
*
* Input:
*
* 4
* / \
* 2 7
* / \ / \
* 1 3 6 9
* Output:
*
* 4
* / \
* 7 2
* / \ / \
* 9 6 3 1
* Trivia:
* This problem was inspired by this original tweet by Max Howell:
*
* Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary
* tree on a whiteboard so f*** off.
*
*/
public class InvertBinaryTree {
public TreeNode invertTree(TreeNode root) {
if (root == null)
return null;
TreeNode left = root.left;
TreeNode right = root.right;
root.left = invertTree(right);
root.right = invertTree(left);
return root;
}
public TreeNode invertTreeOld(TreeNode root) {
helper(root);
return root;
}
private void helper(TreeNode root) {
if (root == null) return;
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
helper(root.left);
helper(root.right);
}
}