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

Commit 06f0a6d

Browse files
Find Leaves of Binary Tree
1 parent ec8a1d0 commit 06f0a6d

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

‎366-find-leaves-of-binary-tree.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/find-leaves-of-binary-tree/
3+
4+
Given the root of a binary tree, collect a tree's nodes as if you were doing this:
5+
Collect all the leaf nodes.
6+
Remove all the leaf nodes.
7+
Repeat until the tree is empty.
8+
9+
Example 1:
10+
Input: root = [1,2,3,4,5]
11+
Output: [[4,5,3],[2],[1]]
12+
Explanation:
13+
[[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per
14+
each level it does not matter the order on which elements are returned.
15+
16+
Example 2:
17+
Input: root = [1]
18+
Output: [[1]]
19+
20+
Constraints:
21+
The number of nodes in the tree is in the range [1, 100].
22+
-100 <= Node.val <= 100
23+
"""
24+
# Definition for a binary tree node.
25+
# class TreeNode:
26+
# def __init__(self, val=0, left=None, right=None):
27+
# self.val = val
28+
# self.left = left
29+
# self.right = right
30+
class Solution:
31+
def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
32+
leaves = []
33+
self.get_height(root, leaves)
34+
return leaves
35+
36+
def get_height(self, root, leaves):
37+
if not root:
38+
return -1
39+
40+
height = 1 + max(self.get_height(root.left, leaves),
41+
self.get_height(root.right, leaves))
42+
if height > len(leaves) - 1:
43+
leaves.append([])
44+
45+
leaves[height].append(root.val)
46+
47+
return height

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /