100. Same Tree
Tags:
Easy
Skills:
Tree
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu kiểm tra hai binary tree có giống nhau về cấu trúc lẫn giá trị tại từng node hay không. Hay tree được gọi là giống nhau nếu
Approach - DFS
Time and space complexity
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 isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
16 if (!p && !q) return true
17 if (!p || !q || p.val !== q.val) return false
18 return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
19};