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

[LeetCode]102 Binary Tree Level Order Traversal

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

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

/**
 * 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>> levelOrder(TreeNode root) {
        
        // This is how we use queue to iterate a tree.
        // To let nodes on the same level be returned in the same list, we can store an extra level for each nodes.
        
        List<List<Integer>> result = new ArrayList<>();
        if (root == null)
            return result;

        Queue<NodeWithLevel> queue = new LinkedList<>();
        queue.offer(new NodeWithLevel(root, 0));
        while (!queue.isEmpty())
        {
            NodeWithLevel nodeWithLevel = queue.poll();
            if (nodeWithLevel.level == result.size())
                result.add(new ArrayList<Integer>());
            result.get(nodeWithLevel.level).add(nodeWithLevel.node.val);
            
            if (nodeWithLevel.node.left != null)
            {
                queue.offer(new NodeWithLevel(nodeWithLevel.node.left, nodeWithLevel.level + 1));
            }
            if (nodeWithLevel.node.right != null)
            {
                queue.offer(new NodeWithLevel(nodeWithLevel.node.right, nodeWithLevel.level + 1));
            }
        }
        
        return result;
    }
    
    private static class NodeWithLevel
    {
        TreeNode node;
        int level;
        NodeWithLevel(TreeNode node, int level)
        {
            this.node = node;
            this.level = level;
        }
    }
}


[LeetCode]102 Binary Tree Level Order Traversal