首页 > 代码库 > Tree

Tree

1 102 Binary Tree Level Order Traverse

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

 

Tree