首页 > 代码库 > [LeetCode]107 Binary Tree Level Order Traversal II

[LeetCode]107 Binary Tree Level Order Traversal II

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