-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvertBinaryTree.java
More file actions
61 lines (51 loc) · 1.67 KB
/
invertBinaryTree.java
File metadata and controls
61 lines (51 loc) · 1.67 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
// * Definition for a binary tree node.
// https://leetcode.com/problems/invert-binary-tree/description/
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 invertBinaryTree {
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
public static void main(String[] args) {
// Create the input binary tree: [4,2,7,1,3,6,9]
TreeNode root = new TreeNode(4);
root.left = new TreeNode(2);
root.right = new TreeNode(7);
root.left.left = new TreeNode(1);
root.left.right = new TreeNode(3);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(9);
// Print the original tree
System.out.println("Original tree:");
printTree(root);
// Invert the tree
invertBinaryTree solution = new invertBinaryTree();
TreeNode invertedRoot = solution.invertTree(root);
// Print the inverted tree
System.out.println("\nInverted tree:");
printTree(invertedRoot);
}
// Helper method to print the tree (in-order traversal)
private static void printTree(TreeNode root) {
if (root == null) return;
printTree(root.left);
System.out.print(root.val + " ");
printTree(root.right);
}
}