Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
1.按照题目中描述的过程,一层一层把叶子节点去掉
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> findLeaves(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(root == null)
return res;
while(!isLeaf(root)) {
List<Integer> list = new ArrayList<Integer>();
helper(res, list, root);
res.add(list);
}
List<Integer> list = new ArrayList<Integer>();
list.add(root.val);
res.add(list);
return res;
}
public void helper(List<List<Integer>> res, List<Integer> list, TreeNode root) {
if(root == null)
return;
if(isLeaf(root.left)) {
list.add(root.left.val);
root.left = null;
} else {
helper(res, list, root.left);
}
if(isLeaf(root.right)) {
list.add(root.right.val);
root.right = null;
} else {
helper(res, list, root.right);
}
}
public boolean isLeaf(TreeNode root) {
if(root == null)
return false;
if(root.left == null && root.right == null)
return true;
return false;
}
}
2.更讲道理的做法,求每个节点的深度,深度定义为左右子节点深度最大值+1,把深度作为index
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> findLeaves(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null)
return res;
helper(res, root);
return res;
}
public int helper(List<List<Integer>> res, TreeNode root) {
if(root == null)
return -1;
int left = helper(res, root.left);
int right = helper(res, root.right);
int depth = Math.max(left, right) + 1;
while(depth >= res.size())
res.add(new ArrayList<Integer>());
res.get(depth).add(root.val);
return depth;
}
}