LeetCode 题解工作台
判断根结点是否等于子结点之和
给你一个 二叉树 的根结点 root ,该二叉树由恰好 3 个结点组成:根结点、左子结点和右子结点。 如果根结点值等于两个子结点值之和,返回 true ,否则返回 false 。 示例 1: 输入: root = [10,4,6] 输出: true 解释: 根结点、左子结点和右子结点的值分别是 10…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 二分·树·traversal
答案摘要
我们直接判断根节点的值是否等于左右子节点的值之和即可。 时间复杂度 ,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给你一个 二叉树 的根结点 root,该二叉树由恰好 3 个结点组成:根结点、左子结点和右子结点。
如果根结点值等于两个子结点值之和,返回 true ,否则返回 false 。
示例 1:
输入:root = [10,4,6] 输出:true 解释:根结点、左子结点和右子结点的值分别是 10 、4 和 6 。 由于 10 等于 4 + 6 ,因此返回 true 。
示例 2:
输入:root = [5,3,1] 输出:false 解释:根结点、左子结点和右子结点的值分别是 5 、3 和 1 。 由于 5 不等于 3 + 1 ,因此返回 false 。
提示:
- 树只包含根结点、左子结点和右子结点
-100 <= Node.val <= 100
解题思路
方法一:直接判断
我们直接判断根节点的值是否等于左右子节点的值之和即可。
时间复杂度 ,空间复杂度 。
# 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 checkTree(self, root: Optional[TreeNode]) -> bool:
return root.val == root.left.val + root.right.val
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(1) because the tree always has three nodes, and space complexity is O(1) for storing references to left and right children without recursion or extra structures. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect a single-step comparison without iteration.
- question_mark
Ask about handling negative values and zero.
- question_mark
Check if candidate considers unnecessary recursion and avoids it.
常见陷阱
外企场景- error
Assuming tree can have more nodes than specified.
- error
Forgetting to handle negative child values correctly.
- error
Using unnecessary recursion or loops for a fixed three-node tree.
进阶变体
外企场景- arrow_right_alt
Check root equals sum of all descendant nodes.
- arrow_right_alt
Extend to N-ary tree with sum of children check.
- arrow_right_alt
Verify sum condition recursively for each subtree.