给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
1.bfs迭代
/**
* 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>> levelOrderBottom(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
if(root == null) return list;
Queue<TreeNode> queue = new LinkedList<>(); //LinkedList类实现了Queue接口
queue.add(root);
while(!queue.isEmpty()){
List<Integer> sub = new ArrayList<>(); //内层list
int len = queue.size();
for (int i = 0;i<len;i++){
TreeNode cur = queue.poll();
sub.add(cur.val);
if(cur.left!=null){
queue.add(cur.left);
}
if(cur.right!=null){
queue.add(cur.right);
}
}
list.add(sub);
// sub.clear();
}
Collections.reverse(list); //翻转
return list;
}
}
2.bfs递归
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
help(root,0,list);
Collections.reverse(list);
return list;
}
public void help(TreeNode root,int depth,List<List<Integer>> res){
if(root == null) return;
if(depth+1>res.size()){ //新的一层新数组空间
res.add(new ArrayList());
}
res.get(depth).add(root.val);
if(root.left!=null) help(root.left,depth+1,res);
if(root.right!=null) help(root.right,depth+1,res);
}
}