Leaf-Similar Trees LeetCode solution in JavaScript

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
* @param {TreeNode} root1
11
* @param {TreeNode} root2
12
* @return {boolean}
13
*/
14

15
var leafSimilar = function (root1, root2) {
16
let array1 = [],
17
array2 = [];
18
let leaf1 = getLeaf(root1, array1),
19
leaf2 = getLeaf(root2, array2);
20

21
if (leaf1.length !== leaf2.length) {
22
// if different lengths, return false right away
23
return false;
24
}
25

26
for (let i = 0; i < leaf1.length; i++) {
27
if (leaf1[i] !== leaf2[i]) {
28
// compare pair by pair
29
return false;
30
}
31
}
32

33
return true;
34
};
35

36
var getLeaf = function (root, array) {
37
// DFS
38
if (!root) {
39
return;
40
}
41
if (!(root.left || root.right)) {
42
array.push(root.val); // push leaf value to the array
43
}
44
getLeaf(root.left, array);
45
getLeaf(root.right, array);
46

47
return array;
48
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0