zoukankan      html  css  js  c++  java
  • 力扣练习004---二叉树的层次遍历(102)

    题目描述:

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

    给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

    例如:
    给定二叉树: [3,9,20,null,null,15,7],

    3
    /
    9 20
    /
    15 7
    返回其层次遍历结果:

    [
    [3],
    [9,20],
    [15,7]
    ]

    题目分析:

    分层遍历,和广度优先搜索的思想不谋而和,比较简单,数据结构使用队列,算法为BFS

    Java代码:

        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<>();
            if (root == null) {
                return result;
            }
    
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            result.add(Collections.singletonList(root.val));
            while (!queue.isEmpty()) {
                int queueSize = queue.size();
                List<Integer> list = new ArrayList<>();
                for (int i = 0; i < queueSize; i++) {
                    TreeNode node = queue.poll();
                    if (node == null) {
                        continue;
                    }
    
                    if (node.left != null) {
                        list.add(node.left.val);
                        queue.offer(node.left);
                    }
                    if (node.right != null) {
                        list.add(node.right.val);
                        queue.offer(node.right);
                    }
                }
    
                if (!list.isEmpty()) {
                    result.add(list);
                }
            }
    
            return result;
        }

    力扣运行结果:

  • 相关阅读:
    16-高级指针
    15-C语言结构体
    14-C语言宏
    13-C语言字符串函数库
    12-C语言字符串
    11-C语言指针
    10-C语言函数
    POJ 1001 高精度乘法
    POJ 1060 多项式乘法和除法取余
    POJ 1318 字典排序
  • 原文地址:https://www.cnblogs.com/sniffs/p/12490784.html
Copyright © 2011-2022 走看看