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

Commit c11e205

Browse files
find leaves of binary tree
1 parent 1119b9f commit c11e205

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package medium;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
import classes.TreeNode;
7+
8+
public class FindLeavesofBinaryTree {
9+
10+
List<List<Integer>> result = new ArrayList<List<Integer>>();
11+
public List<List<Integer>> findLeaves(TreeNode root) {
12+
dfs(root);
13+
return result;
14+
}
15+
16+
int dfs(TreeNode root){
17+
if(root == null) return 0;
18+
int level = Math.max(dfs(root.left), dfs(root.right))+1;
19+
if(result.size() < level){
20+
result.add(new ArrayList<Integer>());
21+
}
22+
result.get(level-1).add(root.val);
23+
return level;
24+
}
25+
26+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
|379|[Design Phone Directory](https://leetcode.com/problems/design-phone-directory/)|[Solution](../../blob/master/MEDIUM/src/medium/DesignPhoneDirectory.java)| O(1)|O(n) | Medium|
3333
|374|[Guess Number Higher or Lower](https://leetcode.com/problems/guess-number-higher-or-lower/)|[Solution](../../blob/master/EASY/src/easy/GuessNumberHigherorLower.java)| O(logn)|O(1) | Easy| Binary Search
3434
|370|[Range Addition](https://leetcode.com/problems/range-addition/)|[Solution](../../blob/master/MEDIUM/src/medium/RangeAddition.java)| O(n+k)|O(1) | Medium|
35+
|366|[Find Leaves of Binary Tree](https://leetcode.com/problems/find-leaves-of-binary-tree/)|[Solution](../../blob/master/MEDIUM/src/medium/FindLeavesofBinaryTree.java)| O(n)|O(h) | Medium| DFS
3536
|359|[Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/)|[Solution](../../blob/master/EASY/src/easy/LoggerRateLimiter.java)| amortized O(1)|O(k) | Easy| HashMap
3637
|350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/)|[Solution](../../blob/master/EASY/src/easy/IntersectionOfTwoArraysII.java)| O(m+n)|O((m+n)) could be optimized | Easy| HashMap, Binary Search
3738
|349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/)|[Solution](../../blob/master/EASY/src/easy/IntersectionOfTwoArrays.java)| O(m+n)|O(min(m,n)) | Easy| Two Pointers, Binary Search

0 commit comments

Comments
 (0)