226. Invert Binary Tree
June 24, 2025
04:32 AM
No headings found
Loading content...
No headings found
Problem
Bài toán yêu cầu bạn đảo ngược (invert) một binary tree, tức là với mỗi node, bạn cần hoán đổi con trái và con phải của nó. Quá trình này phải được thực hiện cho tất cả các node trong cây, tạo thành một ảnh gương (mirror image) của cây ban đầu
Approach
Solution
1/**
2 * Definition for a binary tree node.
3 * class TreeNode {
4 * val: number
5 * left: TreeNode | null
6 * right: TreeNode | null
7 * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8 * this.val = (val===undefined ? 0 : val)
9 * this.left = (left===undefined ? null : left)
10 * this.right = (right===undefined ? null : right)
11 * }
12 * }
13 */
14
15function invertTree(root: TreeNode | null): TreeNode | null {
16 if(root === null) return null;
17 const left = invertTree(root.left);
18 const right = invertTree(root.right);
19
20 root.left = right;
21 root.right = left;
22 return root;
23};