leetcode-----102. 二叉树的层序遍历

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        List<List<Integer>> ans = new ArrayList<>();
        if (root == null) return ans;

        while (!q.isEmpty()) {
            List<Integer> l = new ArrayList<>();
            int sz = q.size();
            for (int i = 0; i < sz; ++i) {
                TreeNode t = q.poll();
                l.add(t.val);
                if (t.left != null) {
                    q.add(t.left);
                }
                if (t.right != null) {
                    q.add(t.right);
                }
            }
            ans.add(l);
        }
        return ans;
    }
}
posted @ 2020-04-05 21:16  景云ⁿ  阅读(64)  评论(0编辑  收藏  举报