码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Level Order Traversal II

时间:2015-01-10 18:19:33      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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]
]

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:

很简单的一道题,就是一个普通的层次遍历,使用一个列表来存储每一层的元素。

Populating Next Right Pointers in Each Node II类似

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> list = new LinkedList<List<Integer>>();//返回结果
        Queue<TreeNode> queue = new LinkedList<TreeNode>();//队列,使用BFS遍历
        int level = 0;//记录某一层进队的元素数
        int count = 0;//计数
        if(root == null){
            return list;
        }
        queue.offer(root);
        level++;
        TreeNode p = null;
        while(queue.size() > 0){
            int nextLevel = 0;//下一层进队的元素数
            List<Integer> tmp = new ArrayList<Integer>();//中间存储每一行的结果
            while(count < level){
                p = queue.poll();//出队
                if(p.left != null){
                    queue.offer(p.left);
                    nextLevel++;
                }
                if(p.right != null){
                    queue.offer(p.right);
                    nextLevel++;
                }
                tmp.add(p.val);
                count ++;
            }
            list.add(0,tmp);
            count = 0;
            level = nextLevel;
        }
        return list;
    }
}

Runtime: 249 ms

Binary Tree Level Order Traversal II

标签:leetcode

原文地址:http://blog.csdn.net/havedream_one/article/details/42583237

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!