|
| 1 | +class BinaryTreeNode { |
| 2 | + int data; |
| 3 | + BinaryTreeNode left, right; |
| 4 | + |
| 5 | + public BinaryTreeNode(int data) { |
| 6 | + this.data = data; |
| 7 | + this.left = this.right = null; |
| 8 | + } |
| 9 | +} |
| 10 | + |
| 11 | +public class BinaryTreeInverter { |
| 12 | + // Time Complexity: O(n). Space Complexity: O(n). |
| 13 | + // Approach: The inverse of an empty tree is an empty tree |
| 14 | + // The inverse of a tree with root r, and subtrees right and left is a tree with |
| 15 | + // root, whose right subtree is the inverse of left and whose left subtree |
| 16 | + // is the inverse of right |
| 17 | + public BinaryTreeNode invertTree(BinaryTreeNode root) { |
| 18 | + if (root != null) { |
| 19 | + root.left = invertTree(root.right); |
| 20 | + root.right = invertTree(root.left); |
| 21 | + } |
| 22 | + return root; |
| 23 | + } |
| 24 | + |
| 25 | + // Time Complexity: O(n). Space Complexity: O(1). |
| 26 | + // Method2: swap pointers |
| 27 | + public BinaryTreeNode invertTree2(BinaryTreeNode root) { |
| 28 | + if (root != null) { |
| 29 | + // swap the pointers in this node |
| 30 | + BinaryTreeNode temp = root.left; |
| 31 | + root.left = root.right; |
| 32 | + root.right = temp; |
| 33 | + |
| 34 | + invertTree2(root.left); |
| 35 | + invertTree2(root.right); |
| 36 | + } |
| 37 | + return root; |
| 38 | + } |
| 39 | + |
| 40 | + // Additional methods or code as needed... |
| 41 | + |
| 42 | + public static void main(String[] args) { |
| 43 | + // Example usage: |
| 44 | + // Construct a binary tree |
| 45 | + BinaryTreeNode root = new BinaryTreeNode(1); |
| 46 | + root.left = new BinaryTreeNode(2); |
| 47 | + root.right = new BinaryTreeNode(3); |
| 48 | + root.left.left = new BinaryTreeNode(4); |
| 49 | + root.left.right = new BinaryTreeNode(5); |
| 50 | + |
| 51 | + BinaryTreeInverter inverter = new BinaryTreeInverter(); |
| 52 | + |
| 53 | + // Invert the binary tree using the first approach |
| 54 | + BinaryTreeNode invertedRoot = inverter.invertTree(root); |
| 55 | + |
| 56 | + // Invert the binary tree using the second approach |
| 57 | + BinaryTreeNode invertedRoot2 = inverter.invertTree2(root); |
| 58 | + |
| 59 | + // Additional code for printing or further usage... |
| 60 | + } |
| 61 | +} |
0 commit comments