法一: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) {
if(root==null) return new ArrayList<List<Integer>>();
List<List<Integer>> res = new LinkedList<List<Integer>>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
List<Integer> tmp = new ArrayList<Integer>();
for(int i=0;i<size;i++){
TreeNode node = queue.poll();
tmp.add(node.val);
if(node.left!=null){
queue.offer(node.left);
}
if(node.right!=null){
queue.offer(node.right);
}
}
res.add(0,tmp);
}
return res;
}
}
法二:DFS
/**
* 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) {
if(root == null ) return new ArrayList<List<Integer>>();
ArrayList res = new ArrayList<ArrayList<Integer>>();
dfs(1, root, res);
return res;
}
public void dfs(int level, TreeNode node, ArrayList<ArrayList<Integer>> res){
if(node == null){
return ;
}
if(level>res.size()){
res.add(0, new ArrayList<Integer>());
}
//res.get(res.size()-1-level+1).add(node.val);
res.get(res.size()-level).add(node.val);
dfs(level+1,node.left,res);
dfs(level+1,node.right,res);
}
}
欢迎大家评论,如果本文对您有帮助,请点个赞,您的点赞对我很重要!这次一定!感谢!!!
转发请注明出处呦!感谢!!!