366-Find-Leaves-of-Binary-Tree
Last updated
Last updated
[] /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<List<Integer>> result;
public List<List<Integer>> findLeaves(TreeNode root) {
result=new ArrayList<>();
if(root==null){
return result;
}
recur(root);
return result;
}
private int recur(TreeNode root){
if(root==null){
return 0;
}
//返回左子树的高度
int left=recur(root.left);
//返回右子树的高度
int right=recur(root.right);
int current=Math.max(left,right)+1;
//如果是新集合,那么就new一个
if(current>result.size()){
result.add(new ArrayList<Integer>());
result.get(result.size()-1).add(root.val);
}else{
//否则通过层数找到对应的集合加入 当前节点
result.get(current-1).add(root.val);
}
return current;
}
}