您可以在树上进行深度优先搜索,而无需一次缓存每个子树的最小值和最大值,但您必须小心,因为比较父级及其子级之间的值不是足够的。例如,在树中:
(10
(7
nil
(20 nil nil)
)
nil
)
根 (10) 的左孩子 (7) 满足不等式 (7 = 7) 的右孩子 (20) 也是如此。但是,这棵树不是 BST(Binary Search Tree),因为 20 不应该在 10 的左子树中。
要解决此问题,您可以遍历传递给指定子树有效间隔的额外参数。
// The valid interval for the subtree root's value is (lower_bound, upper_bound).
bool IsBST(const node_t* tree, int lower_bound, int upper_bound) {
if (tree == NULL) return true; // An empty subtree is OK.
if (tree->value <= lower_bound) return false; // Value in the root is too low.
if (tree->value >= upper_bound) return false; // Value in the root is too high.
// Values at the left subtree should be strictly lower than tree->value
// and be inside the root valid interval.
if (!IsBST(tree->left, lower_bound, tree->value))
return false;
// Values at the left subtree should be strictly greater than tree->value
// and be inside the root valid interval.
if (!IsBST(tree->right, tree->value, upper_bound))
return false;
// Everything is OK, it is a valid BST.
return true;
}
请注意,通过保持原始有效区间,该函数将检测到 20 在该位置无效,因为它不在 (7, 10) 内。第一次调用应该以无限间隔完成,例如:
IsBST(tree, INT_MIN, INT_MAX);
希望这会有所帮助。