---
# System prepended metadata

title: 0366. Find Leaves of Binary Tree
tags: [Leetcode, DFS, Google, Medium]

---

# 0366. Find Leaves of Binary Tree
###### tags: `Leetcode` `Medium` `Google` `DFS`
Link: https://leetcode.com/problems/find-leaves-of-binary-tree/
## 思路 $O(N)$ $O(N)$
recursive

## Code
```java=
class Solution {
    List<List<Integer>> ans;
    public List<List<Integer>> findLeaves(TreeNode root) {
        ans = new ArrayList<>();
        dfs(root);
        return ans;
    }
    private int dfs(TreeNode root){
        if(root==null) return -1;
        int level = 1+Math.max(dfs(root.left),dfs(root.right));
        if(ans.size()<level+1) ans.add(new ArrayList<>());
        ans.get(level).add(root.val);
        return level;
    }
}
```