描述
给定一个二叉树,像这样收集树节点:收集并移除所有叶子,重复,直到树为空。
样例
Given binary tree:
1
/ \
2 3
/ \
4 5
Returns [[4, 5, 3], [2], [1]].
代码
这道题可以采用遍历的方式收集叶子节点,并删除。
/**
* 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>> result=new LinkedList<>();
if(root==null){
return result;
}
while(root!=null){
List<Integer> list=new LinkedList<>();
root=getLeave(root, list);
result.add(list);
}
return result;
}
private TreeNode getLeave(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=getLeave(root.left, list);
root.right=getLeave(root.right, list);
return root;
}
}
390

被折叠的 条评论
为什么被折叠?



