Skip to content

226. Invert Binary Tree 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  TreeNode* invertTree(TreeNode* root) {
    if (!root)
      return nullptr;

    TreeNode* const left = root->left;
    TreeNode* const right = root->right;
    root->left = invertTree(right);
    root->right = invertTree(left);
    return root;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public TreeNode invertTree(TreeNode root) {
    if (root == null)
      return null;

    TreeNode left = root.left;
    TreeNode right = root.right;
    root.left = invertTree(right);
    root.right = invertTree(left);
    return root;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
    if not root:
      return None

    left = root.left
    right = root.right
    root.left = self.invertTree(right)
    root.right = self.invertTree(left)
    return root
Back to top