LeetCode Solutions
226. Invert Binary Tree
Time: $O(n)$ Space: $O(h)$
class 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;
}
};
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;
}
}
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