LeetCode 题解工作台

二叉树的完全性检验

给你一棵二叉树的根节点 root ,请你判断这棵树是否是一棵 完全二叉树 。 在一棵 完全二叉树 中,除了最后一层外,所有层都被完全填满,并且最后一层中的所有节点都尽可能靠左。最后一层(第 h 层)中可以包含 1 到 2 h 个节点。 示例 1: 输入: root = [1,2,3,4,5,6] 输…

category

3

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·树·traversal

bolt

答案摘要

class Solution: def isCompleteTree(self, root: TreeNode) -> bool:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一棵二叉树的根节点 root ,请你判断这棵树是否是一棵 完全二叉树 。

在一棵 完全二叉树 中,除了最后一层外,所有层都被完全填满,并且最后一层中的所有节点都尽可能靠左。最后一层(第 h 层)中可以包含 1 到 2h 个节点。

 

示例 1:

输入:root = [1,2,3,4,5,6]
输出:true
解释:最后一层前的每一层都是满的(即,节点值为 {1} 和 {2,3} 的两层),且最后一层中的所有节点({4,5,6})尽可能靠左。

示例 2:

输入:root = [1,2,3,4,5,null,7]
输出:false
解释:值为 7 的节点不满足条件「节点尽可能靠左」。

 

提示:

  • 树中节点数目在范围 [1, 100]
  • 1 <= Node.val <= 1000
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isCompleteTree(self, root: TreeNode) -> bool:
        q = deque([root])
        while q:
            node = q.popleft()
            if node is None:
                break
            q.append(node.left)
            q.append(node.right)
        return all(node is None for node in q)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Focus on the ability to traverse trees efficiently.

  • question_mark

    Ensure the candidate considers how to handle null nodes and left-to-right order.

  • question_mark

    Evaluate the candidate's awareness of space optimization techniques during traversal.

warning

常见陷阱

外企场景
  • error

    Failing to account for the placement of nodes after encountering null values.

  • error

    Misunderstanding the completeness condition for the last level.

  • error

    Not considering the space complexity and unnecessarily storing large amounts of data during traversal.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modified versions where the tree can be non-binary.

  • arrow_right_alt

    Cases where the tree structure is less balanced, requiring different traversal strategies.

  • arrow_right_alt

    Variation with constraints on tree height, making certain optimization techniques more important.

help

常见问题

外企场景

二叉树的完全性检验题解:二分·树·traversal | LeetCode #958 中等