Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal 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]
]

同样是二叉树广度优先遍历的变形,要求从下面开始记录每一层的节点,我们可以从根节点开始,倒序记录每一层的节点就可以了。代码如下:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        LinkedList<List<Integer>> result = new LinkedList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        if(root == null)
            return result;
        queue.offer(root);
        int helper = 1, count = 0;
        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            list.add(cur.val);
            helper --;
            if(cur.left != null) {
                queue.offer(cur.left);
                count ++;
            }
            if(cur.right != null) {
                queue.offer(cur.right);
                count ++;
            }
            if(helper == 0) {
                result.addFirst(new ArrayList<Integer>(list));
                helper = count;
                count = 0;
                list.clear();
            }
        }
        return result;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2276053