Skip to content

Commit f7d749d

Browse files
committed
Add solution #366
1 parent 7171461 commit f7d749d

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,7 @@
354354
363|[Max Sum of Rectangle No Larger Than K](./solutions/0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard|
355355
364|[Nested List Weight Sum II](./solutions/0364-nested-list-weight-sum-ii.js)|Medium|
356356
365|[Water and Jug Problem](./solutions/0365-water-and-jug-problem.js)|Medium|
357+
366|[Find Leaves of Binary Tree](./solutions/0366-find-leaves-of-binary-tree.js)|Medium|
357358
367|[Valid Perfect Square](./solutions/0367-valid-perfect-square.js)|Easy|
358359
368|[Largest Divisible Subset](./solutions/0368-largest-divisible-subset.js)|Medium|
359360
371|[Sum of Two Integers](./solutions/0371-sum-of-two-integers.js)|Medium|
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 366. Find Leaves of Binary Tree
3+
* https://leetcode.com/problems/find-leaves-of-binary-tree/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary tree, collect a tree's nodes as if you were doing this:
7+
* - Collect all the leaf nodes.
8+
* - Remove all the leaf nodes.
9+
* - Repeat until the tree is empty.
10+
*/
11+
12+
/**
13+
* Definition for a binary tree node.
14+
* function TreeNode(val, left, right) {
15+
* this.val = (val===undefined ? 0 : val)
16+
* this.left = (left===undefined ? null : left)
17+
* this.right = (right===undefined ? null : right)
18+
* }
19+
*/
20+
/**
21+
* @param {TreeNode} root
22+
* @return {number[][]}
23+
*/
24+
var findLeaves = function(root) {
25+
const levels = [];
26+
getHeight(root);
27+
return levels;
28+
29+
function getHeight(node) {
30+
if (!node) return -1;
31+
32+
const leftHeight = getHeight(node.left);
33+
const rightHeight = getHeight(node.right);
34+
const height = Math.max(leftHeight, rightHeight) + 1;
35+
36+
if (levels.length <= height) {
37+
levels.push([]);
38+
}
39+
levels[height].push(node.val);
40+
41+
return height;
42+
}
43+
};

0 commit comments

Comments
 (0)