递归传 (low, high) 开区间,中序遍历必须严格递增。
OJ: leetcodecn
题目 ID: validate-binary-search-tree
难度:普及+/提高
标签:BST递归cpppython
日期: 2026-07-29 13:10
题意
判断二叉树是否为有效的 BST。
思路
递归传上下界,每个节点值必须在 (lo, hi) 开区间内。中序遍历检验严格递增也行。
代码
cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
bool isValidBST(TreeNode *root) {
// 每个节点都必须落在所有祖先共同限定的开区间内。
function<bool(TreeNode *, long, long)> dfs = [&](TreeNode *r, long lo, long hi) {
if (!r)
return true;
if (r->val <= lo || r->val >= hi)
return false;
return dfs(r->left, lo, r->val) && dfs(r->right, r->val, hi);
};
return dfs(root, LONG_MIN, LONG_MAX);
}
};
TreeNode *build(istream &in, int n) {
if (!n)
return nullptr;
vector<TreeNode *> nodes(n);
queue<TreeNode *> q;
for (int i = 0, v; i < n; i++) {
in >> v;
if (v != -1)
nodes[i] = new TreeNode(v);
}
TreeNode *root = nodes[0];
if (root)
q.push(root);
int idx = 1;
while (!q.empty() && idx < n) {
auto cur = q.front();
q.pop();
if (idx < n) {
cur->left = nodes[idx];
if (nodes[idx])
q.push(nodes[idx]);
idx++;
}
if (idx < n) {
cur->right = nodes[idx];
if (nodes[idx])
q.push(nodes[idx]);
idx++;
}
}
return root;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
auto r = build(cin, n);
cout << Solution().isValidBST(r) << '\n';
return 0;
}python
#!/usr/bin/env python3
from collections import deque
from typing import Optional
class TreeNode:
def __init__(self, x):
self.val = x
self.left = self.right = None
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def dfs(r, lo, hi):
if not r:
return True
if r.val <= lo or r.val >= hi:
return False
return dfs(r.left, lo, r.val) and dfs(r.right, r.val, hi)
return dfs(root, float("-inf"), float("inf"))
def build(arr):
if not arr:
return None
nodes = [TreeNode(v) if v != -1 else None for v in arr]
q = deque([nodes[0]]) if nodes[0] else deque()
idx = 1
while q and idx < len(arr):
cur = q.popleft()
if idx < len(arr):
cur.left = nodes[idx]
if nodes[idx]:
q.append(nodes[idx])
idx += 1
if idx < len(arr):
cur.right = nodes[idx]
if nodes[idx]:
q.append(nodes[idx])
idx += 1
return nodes[0]
def main():
n = int(input())
a = list(map(int, input().split()))
print(Solution().isValidBST(build(a)))
if __name__ == "__main__":
main()复杂度
时间 O(n),空间 O(height)。
总结
BST 的递归定义就是检验算法:左子树所有值 < 根 < 右子树所有值。