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

Binary Tree Level Order Traversal

时间:2015-03-15 16:29:32      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

Binary Tree Level Order Traversal

问题:

  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).

思路:

  bfs

我的代码:

技术分享
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> rst = new ArrayList<List<Integer>>();
        if(root == null) return rst;
        
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while(!queue.isEmpty())
        {
            int size = queue.size();
            List<Integer> list = new ArrayList<Integer>();
            for(int i = 0; i < size; i++)
            {
                TreeNode node = queue.poll();
                list.add(node.val);
                if(node.left != null)
                    queue.offer(node.left);
                if(node.right != null)
                    queue.offer(node.right);
            }
            rst.add(list);
        }
        // Collections.reverse(rst);
        return rst;
    }
}
View Code

 

Binary Tree Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4339820.html

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