天天看点

leetcode第42题(binary-tree-level-order-traversal-ii)

题目:

Given a binary tree, return the bottom-up level ordertraversal of its nodes' values. (ie, from left to right, level by level from leaf to root). 

For example:

Given binary tree{3,9,20,#,#,15,7}, 

3
   / \
  9  20
    /  \
   15   7
      

return its bottom-up level order traversal as: 

[
  [15,7]
  [9,20],
  [3],
]
      

confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below. 

Here's an example: 

1
  / \
 2   3
    /
   4
    \
     5
      

The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}". 

思路:

其实是树的层次遍历,只是每次是从底向上输出的答案的,因而在得到每层的结果时,添加的位置是list的头部。由于每层遍历是先输出左子树,再输出右子树的顺序,因而我们使用队列存储下一层的节点。

代码:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if(root==null){
            return result;
        }
        Queue<TreeNode> que = new LinkedList<TreeNode>();
        que.add(root);
        while(!que.isEmpty()){
            int count = que.size();
            ArrayList<Integer> list = new ArrayList<Integer>();
            for(int i=0;i<count;i++){
                TreeNode node = que.poll();
                list.add(node.val);
                if(node.left!=null){
                    que.add(node.left);
                }
                if(node.right != null){
                    que.add(node.right);
                }
            }
            result.add(0,list);
        }
        return result;
    }
}
      

继续阅读