-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInvertBinaryTree.java
More file actions
60 lines (46 loc) · 1.39 KB
/
Copy pathInvertBinaryTree.java
File metadata and controls
60 lines (46 loc) · 1.39 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
// Invert a binary tree.
// See: https://leetcode.com/problems/invert-binary-tree/
package leetcode.tree;
import static leetcode.util.tree.BinTreeUtil.*;
import leetcode.util.tree.TreeNode;
public class InvertBinaryTree {
/**
* Uses a helper class that modifies the tree
*/
public TreeNode invertTree_1(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);
}
/**
* Inverts a tree without helper
* @return the root directly from the recursion
*/
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
invertTree(root.left);
invertTree(root.right);
return root;
}
public static void main(String[] args) {
InvertBinaryTree sln = new InvertBinaryTree();
TreeNode t1 = initTree(4, 2, 7, 1, 3, 6, 9);
TreeNode t2 = initTree(1);
TreeNode t3 = initTree(1, 2);
printInorder(sln.invertTree(t1));
printInorder(sln.invertTree(t2));
printInorder(sln.invertTree(null));
printInorder(sln.invertTree(t3));
}
}