美文网首页
102. 二叉树的层序遍历

102. 二叉树的层序遍历

作者: justonemoretry | 来源:发表于2021-08-24 21:04 被阅读0次
image.png

解法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        q.offer(root);
        while (!q.isEmpty()) {
            long size = q.size();
            List<Integer> level = new ArrayList<>();
            // 取出队列中当前有的元素
            for (int i = 0; i < size; i++) {
                TreeNode node = q.poll();
                level.add(node.val);
                // 子节点放到下一层
                if (node.left != null) {
                    q.offer(node.left);
                }
                if (node.right != null) {
                    q.offer(node.right);
                }
            }
            res.add(level);
        }
        return res;
    }
}

相关文章

网友评论

      本文标题:102. 二叉树的层序遍历

      本文链接:https://www.haomeiwen.com/subject/ehfriltx.html