1. 程式人生 > >題目:二叉樹的層次遍歷 II

題目:二叉樹的層次遍歷 II

/**
* 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: buttom-up level order a list of lists of integer
     */
    public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
        // write your code here
         ArrayList<ArrayList<Integer>> res  = new ArrayList<>();
          if(null==root) return res;
          Queue<TreeNode> fQ = new LinkedList<>();
          fQ.add(root);
          while(fQ!=null&&fQ.size()>0){
              Queue<TreeNode> sQ = new LinkedList<>();
             ArrayList<Integer> depthRoot  = new ArrayList<>();
              while(fQ!=null&&fQ.size()>0){
                   TreeNode  cur = fQ.poll();
                   depthRoot.add(cur.val);
                   if(cur.left!=null){
                        sQ.add(cur.left);
                   }
                   if(cur.right!=null){
                        sQ.add(cur.right);
                   }
              }
              res.add(depthRoot);
              fQ = sQ;
          }         
          return reverse(res);        
     }
     public ArrayList<ArrayList<Integer>>  reverse(ArrayList<ArrayList<Integer>> res){
         ArrayList<ArrayList<Integer>>  reres = new ArrayList<>();
         for(int i=res.size()-1;i>=0;i--){
              ArrayList<Integer> tmp = res.get(i);
              reres.add(tmp);
         }
         return reres;
    }
}