Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit f997462

Browse files
committed
Add solution #872
1 parent b5b3a7d commit f997462

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

0872-leaf-similar-trees.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 872. Leaf-Similar Trees
3+
* https://leetcode.com/problems/leaf-similar-trees/
4+
* Difficulty: Easy
5+
*
6+
* Consider all the leaves of a binary tree, from left to right order, the values of
7+
* those leaves form a leaf value sequence.
8+
*
9+
* For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
10+
*
11+
* Two binary trees are considered leaf-similar if their leaf value sequence is the same.
12+
*
13+
* Return true if and only if the two given trees with head nodes root1 and root2 are
14+
* leaf-similar.
15+
*/
16+
17+
/**
18+
* Definition for a binary tree node.
19+
* function TreeNode(val, left, right) {
20+
* this.val = (val===undefined ? 0 : val)
21+
* this.left = (left===undefined ? null : left)
22+
* this.right = (right===undefined ? null : right)
23+
* }
24+
*/
25+
/**
26+
* @param {TreeNode} root1
27+
* @param {TreeNode} root2
28+
* @return {boolean}
29+
*/
30+
var leafSimilar = function(root1, root2) {
31+
return traverse(root1, []).toString() === traverse(root2, []).toString();
32+
};
33+
34+
function traverse(root, result) {
35+
if (!root.left && !root.right) {
36+
result.push(root.val);
37+
}
38+
if (root.left) {
39+
traverse(root.left, result);
40+
}
41+
if (root.right) {
42+
traverse(root.right, result);
43+
}
44+
return result;
45+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,7 @@
257257
844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy|
258258
846|[Hand of Straights](./0846-hand-of-straights.js)|Medium|
259259
867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy|
260+
872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy|
260261
876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy|
261262
884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy|
262263
890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium|

0 commit comments

Comments
 (0)