Skip to content
AI360Xpert
Back to Trees
Easy

Invert Binary Tree

Given the `root` of a binary tree, invert the tree, and return its root. Inverting a binary tree means swapping every left node with its corresponding right node.

Examples

Input:root = [4,2,7,1,3,6,9]
Output:[4,7,2,9,6,3,1]
Input:root = [2,1,3]
Output:[2,3,1]

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

Approach

Use a recursive Depth-First Search (DFS) approach. The base case is when the current node is null, we return null. For a non-null node, we swap its left and right child pointers. Then, we recursively invert its left and right subtrees. Finally, return the current node.

Complexity Analysis

Time Complexity
O(n)
Space Complexity
O(h)

Where n is the number of nodes and h is the height of the tree. The space complexity is due to the recursion stack.

Solution.java
/** * Definition for a binary tree node. * public 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; *     } * } */class Solution {    public TreeNode invertTree(TreeNode root) {        if (root == null) {            return null;        }                // Swap the children        TreeNode temp = root.left;        root.left = root.right;        root.right = temp;                // Recursively invert the subtrees        invertTree(root.left);        invertTree(root.right);                return root;    }}