Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit0582fd2

Browse files
authored
Create 0872-leaf-similar-trees.js
1 parent80a12e6 commit0582fd2

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎javascript/0872-leaf-similar-trees.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* DFS | Preorder Traversal
11+
* Time O(n) | Space O(n)
12+
* https://leetcode.com/problems/leaf-similar-trees/
13+
*@param {TreeNode} root1
14+
*@param {TreeNode} root2
15+
*@return {boolean}
16+
*/
17+
varleafSimilar=function(root1,root2){
18+
19+
constdfs=(node,arr)=>{
20+
if(!node.left&&!node.right){
21+
arr.push(node.val);
22+
returnarr;
23+
}
24+
if(node.left)dfs(node.left,arr);
25+
if(node.right)dfs(node.right,arr);
26+
27+
returnarr;
28+
}
29+
30+
constarr1=dfs(root1,[]);
31+
constarr2=dfs(root2,[]);
32+
33+
if(arr1.length!==arr2.length)returnfalse;
34+
35+
for(leti=0;i<arr1.length;i++){
36+
if(arr1[i]!==arr2[i])returnfalse;
37+
}
38+
39+
returntrue;
40+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp