auto-generated entry for Invert Binary Tree. the solution files are available below.
solution files
- C++
invert-binary-tree/synced-solution.cpp - Python
invert-binary-tree/synced-solution.py - TypeScript
invert-binary-tree/synced-solution.ts
Collected C++, Python, TypeScript solutions for invert binary tree. Add a dedicated write-up later if you want deeper notes.
auto-generated entry for Invert Binary Tree. the solution files are available below.
invert-binary-tree/synced-solution.cppinvert-binary-tree/synced-solution.pyinvert-binary-tree/synced-solution.tsclass TreeNode:
def __init__(self, val=class="syntax-number">0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def invertTree(root: TreeNode) -> TreeNode:
if not root:
return None
root.left, root.right = root.right, root.left
invertTree(root.left)
invertTree(root.right)
return root
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root) return nullptr;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
function invertTree(root: TreeNode | null): TreeNode | null {
if (!root) return null;
[root.left, root.right] = [root.right, root.left];
invertTree(root.left);
invertTree(root.right);
return root;
}