226. Invert Binary Tree ¶ Time: $O(n)$ Space: $O(h)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13class Solution { public: TreeNode* invertTree(TreeNode* root) { if (root == nullptr) 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 12class 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 10class Solution: def invertTree(self, root: TreeNode | None) -> TreeNode | None: if not root: return None left = root.left right = root.right root.left = self.invertTree(right) root.right = self.invertTree(left) return root