Binary Tree Level Order Traversal

题目
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:

Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]

答案

public class Solution {
    public List> levelOrder(TreeNode root) {
        if(root == null) return new ArrayList>(); ;
        Queue q = new LinkedList();
        List> lists = new ArrayList>();
        q.offer(root);
        while(q.size() != 0) {
            int curr_size = q.size();
            List temp = new ArrayList();
            for(int i = 0; i < curr_size; i++) {
                TreeNode t = q.poll();
                temp.add(t.val);
                if(t.left != null) q.offer(t.left);
                if(t.right != null) q.offer(t.right);
            }
            lists.add(temp);
        }
        return lists;
    }
}

你可能感兴趣的:(Binary Tree Level Order Traversal)