LeetCode 题解工作台
验证二叉树
二叉树上有 n 个节点,按从 0 到 n - 1 编号,其中节点 i 的两个子节点分别是 leftChild[i] 和 rightChild[i] 。 只有 所有 节点能够形成且 只 形成 一颗 有效的二叉树时,返回 true ;否则返回 false 。 如果节点 i 没有左子节点,那么 leftC…
6
题型
4
代码语言
3
相关题
当前训练重点
中等 · 图·DFS·traversal
答案摘要
我们可以遍历每个节点 以及对应的左右孩子 , ,用 数组记录节点是否有父节点: - 若孩子节点已存在父节点,说明有多个父亲,不满足条件,直接返回 `false`。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 图·DFS·traversal 题型思路
题目描述
二叉树上有 n 个节点,按从 0 到 n - 1 编号,其中节点 i 的两个子节点分别是 leftChild[i] 和 rightChild[i]。
只有 所有 节点能够形成且 只 形成 一颗 有效的二叉树时,返回 true;否则返回 false。
如果节点 i 没有左子节点,那么 leftChild[i] 就等于 -1。右子节点也符合该规则。
注意:节点没有值,本问题中仅仅使用节点编号。
示例 1:

输入:n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1] 输出:true
示例 2:

输入:n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1] 输出:false
示例 3:

输入:n = 2, leftChild = [1,0], rightChild = [-1,-1] 输出:false
提示:
n == leftChild.length == rightChild.length1 <= n <= 104-1 <= leftChild[i], rightChild[i] <= n - 1
解题思路
方法一:并查集
我们可以遍历每个节点 以及对应的左右孩子 , ,用 数组记录节点是否有父节点:
- 若孩子节点已存在父节点,说明有多个父亲,不满足条件,直接返回
false。 - 若孩子节点与父节点已经处于同一个连通分量,说明会形成环,不满足条件,直接返回
false。 - 否则,进行合并,并且将 数组对应位置置为
true,同时将连通分量个数减去 。
遍历结束,判断并查集中连通分量个数是否为 ,若是返回 true,否则返回 false。
时间复杂度 ,空间复杂度 。其中 为节点个数,而 为阿克曼函数的反函数,即反阿克曼函数,其值小于 。
class Solution:
def validateBinaryTreeNodes(
self, n: int, leftChild: List[int], rightChild: List[int]
) -> bool:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
p = list(range(n))
vis = [False] * n
for i, (a, b) in enumerate(zip(leftChild, rightChild)):
for j in (a, b):
if j != -1:
if vis[j] or find(i) == find(j):
return False
p[find(i)] = find(j)
vis[j] = True
n -= 1
return n == 1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Look for an understanding of tree structure properties and cycle detection.
- question_mark
Check if the candidate handles edge cases like multiple roots or nodes with no parents.
- question_mark
Evaluate how efficiently the candidate applies DFS and parent tracking to solve the problem.
常见陷阱
外企场景- error
Failing to handle cycles correctly in the graph can lead to incorrect results.
- error
Incorrectly identifying the root node, especially in cases where there is more than one root.
- error
Not accounting for the scenario where nodes might not form a connected structure.
进阶变体
外企场景- arrow_right_alt
What if the binary tree is sparse or very large? Can your solution handle it efficiently?
- arrow_right_alt
How would you handle the case where some nodes are missing their children?
- arrow_right_alt
Can you modify the solution to identify the specific type of error (cycle, multiple roots, etc.)?