Skip to content

Commit ae1a296

Browse files
committed
366_Find_Leaves_of_Binary_Tree
1 parent e53d29b commit ae1a296

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,7 @@ Check this [golden](https://tinyurl.com/ujopecz) post.
474474
|42| [1305. All Elements in Two Binary Search Trees](https://tinyurl.com/undhmra) | [Python](https://tinyurl.com/wu6rdaw/1305_All_Elements_in_Two_Binary_Search_Trees.py), [Swift](https://tinyurl.com/wuja3c4/1305_All_Elements_in_Two_Binary_Search_Trees.swift) | -- | Medium | -- |
475475
|43| [536. Construct Binary Tree from String](https://tinyurl.com/yyl5vuh7) | [Python](https://tinyurl.com/wu6rdaw/536_Construct_Binary_Tree_from_String.py), [Swift](https://tinyurl.com/wuja3c4/536_Construct_Binary_Tree_from_String.swift) | -- | Medium | -- |
476476
|44| [652. Find Duplicate Subtrees](https://tinyurl.com/y5zt6392) | [Python](https://tinyurl.com/wu6rdaw/652_Find_Duplicate_Subtrees.py), [Swift](https://tinyurl.com/wuja3c4/652_Find_Duplicate_Subtrees.swift) | -- | Medium | -- |
477+
|45| [366. Find Leaves of Binary Tree](https://tinyurl.com/yjaqjjyc) | [Swift](https://tinyurl.com/wuja3c4/366_Find_Leaves_of_Binary_Tree.swift) | -- | Medium | -- |
477478

478479
</p>
479480
</details>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
func findLeaves(_ root: TreeNode?) -> [[Int]] {
3+
var result = [[Int]]()
4+
getHeight(root, &result)
5+
return result
6+
}
7+
8+
@discardableResult
9+
func getHeight(_ root: TreeNode?, _ leaves: inout [[Int]]) -> Int {
10+
guard let root = root else {
11+
return -1
12+
}
13+
14+
let (left, right) = (getHeight(root.left, &leaves), getHeight(root.right, &leaves))
15+
let height = max(left, right) + 1
16+
if height < leaves.count {
17+
leaves[height].append(root.val)
18+
} else {
19+
leaves.append([root.val])
20+
}
21+
return height
22+
}
23+
}

0 commit comments

Comments
 (0)