算法初探LeetCode-二叉树的层序遍历

87 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 5 天,点击查看活动详情

LeetCode102:二叉树的层序遍历

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

示例 1:

tree1.jpg

输入: root = [3,9,20,null,null,15,7]
输出: [[15,7],[9,20],[3]]

示例 2:

输入: root = [1]
输出: [[1]]

示例 3:

输入: root = []
输出: []

提示:

  • 树中节点数目在范围 [0, 2000] 内
  • -1000 <= Node.val <= 1000

思路分析

根据题意分析采用的是队列方式。

  • 首先将root offer进queue中,再将null插到队列尾部,表示层级的结束; 进行while判断(当队列的首个元素为null则需要进行判断,如果队列长度不为1证明还有元素仍需要进行循环,若长度为1则代表队列结束) 若队列首个元素为null,则代表上一层级为0,则需要进行以下步骤:
  • 1.需要把上一层级的list(tempResult)加入result;
  • 2.将tempResult进行初始化;
  • 3.将队列元素进行poll弹出
  • 4.重新offer如一个null,在null之前则是一个层级!能够区分一个个层级 若不为null,则从队列中将元素弹出,并把该结点左右不为null的结点offer进队列中 最后当跳出while循环的时候,需要把tempresult添加进result中

算法代码

public List < List < Integer >> levelOrder(TreeNode root) {
    List < List < Integer >> result = new ArrayList < List < Integer >> ();
    if (root == null) {
        return result;
    }
    Queue < TreeNode > tempQueue = new LinkedList < > ();
    tempQueue.offer(root);
    tempQueue.offer(null);
    List < Integer > tempResult = new ArrayList < > ();
    while ((tempQueue.peek() == null && tempQueue.size() != 1) || tempQueue.peek() != null) {
        if (tempQueue.peek() == null) {
            result.add(tempResult);
            tempResult = new ArrayList < > ();
            tempQueue.poll();
            tempQueue.offer(null);
            continue;
        }
        root = tempQueue.peek();
        tempResult.add(root.val);
        tempQueue.poll();
        if (root.left != null) {
            tempQueue.offer(root.left);
        }
        if (root.right != null) {
            tempQueue.offer(root.right);
        }
    }
    result.add(tempResult);
    return result;
}

结果详情

Snipaste_2023-02-08_23-05-40.png

算法复杂度

  • 空间复杂度:O(1)O(1)
  • 时间复杂度:O(n)O(n)

掘金(JUEJIN)一起进步,一起成长!