
Leetcode Problem 226: Invert Binary Tree
Given the root of a binary tree, invert the tree (produce its mirror image) by recursively swapping the left and right subtrees of every node, and return the root.
4 4
/ \ --> / \
2 7 7 2
/ \ / \ / \ / \
1 3 6 9 9 6 3 1
Constraints:
export class TreeNode {
val: number
left: TreeNode | null
right: TreeNode | null
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = (val === undefined ? 0 : val)
this.left = (left === undefined ? null : left)
this.right = (right === undefined ? null : right)
}
}
function invertTree(root: TreeNode | null): TreeNode | null {
if (root === null) {
return root
}
const leftNode = invertTree(root.left)
const rightNode = invertTree(root.right)
root.left = rightNode
root.right = leftNode
return root
}