Blind 75

Invert Binary Tree

Problem
LC 226
Category
Tree
File
blind75_LC226InvertBinaryTree.java
Path
pkg5leetcode/blind75/blind75_LC226InvertBinaryTree.java
Package
pkg5leetcode.blind75
Command
java pkg5leetcode/blind75/blind75_LC226InvertBinaryTree.java
Approach
Swap children recursively at each node.
Complexity
Time O(n), Space O(h)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/blind75/blind75_LC226InvertBinaryTree.java
1package pkg5leetcode.blind75;2 3/*4 * Invert Binary Tree | LC 2265 * APPROACH: Swap children recursively at each node.6 * COMPLEXITY: Time O(n), Space O(h)7 */8public class blind75_LC226InvertBinaryTree {9    /** Same shape as pkg5leetcode/common/TreeNode.java (nested for single-file runs). */10 11    static class TreeNode {12        int val;13        TreeNode left, right;14        TreeNode(int val) { this.val = val; }15    }16 17    static TreeNode invertTree(TreeNode root) {18        if (root == null) return null;19        TreeNode t = root.left;20        root.left = invertTree(root.right);21        root.right = invertTree(t);22        return root;23    }24 25    public static void main(String[] args) {26        TreeNode root = new TreeNode(4);27        root.left = new TreeNode(2);28        root.right = new TreeNode(7);29        root.left.left = new TreeNode(1);30        root.left.right = new TreeNode(3);31        invertTree(root);32        check(root.left.val == 7 && root.right.val == 2, "case1");33        check(invertTree(null) == null, "case2");34        System.out.println("all tests passed");35    }36 37    static void check(boolean cond, String name) {38        if (!cond) throw new AssertionError("FAILED: " + name);39        System.out.println("  PASS " + name);40    }41}