-
Notifications
You must be signed in to change notification settings - Fork 0
/
InvertBinaryTrees.java
50 lines (36 loc) · 1.19 KB
/
InvertBinaryTrees.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
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class InvertBinaryTrees {
public static TreeNode invertTree(TreeNode root) {
if (root == null)
return null; // this is the end of a root/leaf
TreeNode left = invertTree(root.left);
TreeNode right = invertTree(root.right);
root.left = right;
root.right = left;
if (left != null) System.out.print(left.val + " ");
if (right != null) System.out.print(right.val + " ");
return root;
}
public static void main(String args[]) {
TreeNode leaf1 = new TreeNode(1);
TreeNode leaf2 = new TreeNode(3);
TreeNode leaf3 = new TreeNode(6);
TreeNode leaf4 = new TreeNode(9);
TreeNode leftNode = new TreeNode(2, leaf1, leaf2);
TreeNode rightNode = new TreeNode(7, leaf3, leaf4);
TreeNode root = new TreeNode(4, leftNode, rightNode);
// built tree from leetcode example.
System.out.println(invertTree(root).val);
}
}