Skip to content

Commit 2377648

Browse files
committed
feat: add Same Tree
1 parent 45fdcac commit 2377648

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ Roadmap: https://neetcode.io/roadmap
6262
| 104 | [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/description/) | Easy | [ts](./TypeScript/104.maximum-depth-of-binary-tree.ts) | Trees |
6363
| 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | Easy | [ts](./TypeScript/543.diameter-of-binary-tree.ts) | Trees |
6464
| 110 | [Balanced Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) | Easy | [ts](./TypeScript/110.balanced-binary-tree.ts) | Trees |
65+
| 100 | [ Same Tree](https://leetcode.com/problems/same-tree/description/) | Easy | [ts](./TypeScript/100.same-tree.ts) | Trees |
6566
| 102 | [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/) | Medium | [ts](./TypeScript/102.binary-tree-level-order-traversal.ts) | Trees |
6667
| 46 | [Permutations](https://leetcode.com/problems/permutations/) | Medium | [ts](./TypeScript/46.permutations.ts) | Backtracking |
6768

TypeScript/100.same-tree.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class TreeNode {
2+
val: number;
3+
left: TreeNode | null;
4+
right: TreeNode | null;
5+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
6+
this.val = val === undefined ? 0 : val;
7+
this.left = left === undefined ? null : left;
8+
this.right = right === undefined ? null : right;
9+
}
10+
}
11+
12+
function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
13+
if (p === null && q === null) {
14+
return true;
15+
}
16+
17+
if (p === null || q === null) {
18+
return false;
19+
}
20+
21+
return (
22+
p.val === q.val &&
23+
isSameTree(p.left, q.left) &&
24+
isSameTree(p.right, q.right)
25+
);
26+
}
27+
28+
const tree1 = new TreeNode(
29+
3,
30+
new TreeNode(9),
31+
new TreeNode(20, new TreeNode(15), new TreeNode(7))
32+
);
33+
const tree2 = new TreeNode(
34+
3,
35+
new TreeNode(9),
36+
new TreeNode(20, new TreeNode(15), new TreeNode(7))
37+
);
38+
39+
console.log(isSameTree(tree1, tree2));

0 commit comments

Comments
 (0)