正常层次遍历步骤,然后把结果reverse一下
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param root TreeNode类 * @return int整型ArrayList<ArrayList<>> */ public ArrayList<ArrayList<Integer>> levelOrderBottom (TreeNode root) { // write code here ArrayList<ArrayList<Integer>> temp = new ArrayList<>(); if(root==null) return temp; Queue<TreeNode> q = new LinkedList<>(); q.offer(root); while(!q.isEmpty()){ int size = q.size(); ArrayList<Integer> path = new ArrayList<>(); while(size > 0 ){ TreeNode n = q.remove(); path.add(n.val); if(n.left!=null) q.offer(n.left); if(n.right!=null) q.offer(n.right); size--; } temp.add(new ArrayList<>(path)); } ArrayList<ArrayList<Integer>> res = new ArrayList<>(); for(int i = temp.size()-1 ; i >= 0 ; i--) res.add(temp.get(i)); return res; } }