LintCode 70. 二叉树的层次遍历 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: A tree
    * @return: buttom-up level order a list of lists of integer
    */
   public List<List<Integer>> levelOrderBottom(TreeNode root) {
      // write your code here
      List<List<Integer>> list = new ArrayList<>();
      LinkedList<TreeNode> queue = new LinkedList<>();
      if (root != null) {
         queue.offer(root);
      }
      while (!queue.isEmpty()) {
         int len = queue.size();
         List<Integer> tmpList = new ArrayList<>();
         while (len > 0) {
            TreeNode treeNode = queue.poll();
            tmpList.add(treeNode.val);
            if (treeNode.left != null) {
               queue.offer(treeNode.left);
            }
            if (treeNode.right != null) {
               queue.offer(treeNode.right);
            }
            len--;
         }
         list.add(tmpList);
      }
      List<List<Integer>> returnList = new ArrayList<>();
      for (int i = list.size() - 1; i >= 0; i--) {
         returnList.add(list.get(i));
      }
      return returnList;
   }
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页