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

[LeetCode]107 Binary Tree Level Order Traversal II

时间:2015-01-06 15:49:37      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/

http://blog.csdn.net/linhuanmars/article/details/23414711

/**
 * 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) {
        // BFS
        if (root == null)
            return Collections.<List<Integer>> emptyList();
            
        List<List<Integer>> toReturn = new ArrayList<>();
        Queue<TreeNodeWithLevel> queue = new LinkedList<TreeNodeWithLevel>();
        queue.offer(new TreeNodeWithLevel(root, 1));
        while (!queue.isEmpty())
        {
            TreeNodeWithLevel n = queue.poll();
            if (toReturn.size() < n.level)
            {
                toReturn.add(0, new ArrayList<Integer>());
            }
            toReturn.get(toReturn.size() - n.level).add(n.node.val);
            if (n.node.left != null)
            {
                queue.offer(new TreeNodeWithLevel(n.node.left, n.level + 1));
            }
            if (n.node.right != null)
            {
                queue.offer(new TreeNodeWithLevel(n.node.right, n.level + 1));
            }
        }
        return toReturn;
    }
    
    private static class TreeNodeWithLevel
    {
        int level;
        TreeNode node;
        TreeNodeWithLevel(TreeNode node, int level)
        {
            this.node = node;
            this.level = level;
        }
    }
}


[LeetCode]107 Binary Tree Level Order Traversal II

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1599696

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