题目:
分析:遍历二叉树,找到叶子结点后,将其加入到list中,然后将叶节点置为null,重复,直到root=null为止。这样可以一层层剥离开来。
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /* * @param root: the root of binary tree * @return: collect and remove all leaves */ public List<List<Integer>> findLeaves(TreeNode root) { // write your code here List<List<Integer>> res=new ArrayList<>(); if(root==null) return res; while(root!=null){ List<Integer> arr=new ArrayList<>(); root=getLeaves(root,arr); res.add(arr); } return res; } public TreeNode getLeaves(TreeNode root,List<Integer> list){ if(root==null) return null; if(root.left==null && root.right==null){ list.add(root.val); return null; } root.left=getLeaves(root.left,list); root.right=getLeaves(root.right,list); return root; } }