如何在 C# 中使用递归检查二叉树是否为有效的二叉搜索树?
csharpserver side programmingprogramming更新于 2025/4/18 6:07:17
如果一棵树的所有左子节点都小于节点元素,并且所有右子节点都大于节点元素,则该树为二叉搜索树。首先,我们检查节点是否有任何值,如果节点为空,则我们认为它是有效的二叉搜索树并返回 true。检查节点为空结果后,我们通过传递节点、最小值和最大值来调用递归方法 isValidBST。如果根值小于最小值且根值大于 最大值,我们认为它不是二叉搜索树并返回 false,否则我们通过传递左值和右值递归调用 isValidBST 方法,直到检查完所有节点
示例
public class TreesPgm{
public class Node{
public int Value;
public Node LeftChild;
public Node RightChild;
public Node(int value){
this.Value = value;
}
public override String ToString(){
return "Node=" + Value;
}
}
public bool isValidBST(Node root){
if (root == null){
return true;
}
return isValidBST(root, int.MinValue, int.MaxValue);
}
private bool isValidBST(Node root, int min, int max){
if (root == null){
return true;
}
if (root.Value <= min || root.Value >= max){
return false;
}
return isValidBST(root.LeftChild, min, root.Value) && isValidBST(root.RightChild,
root.Value, max);
}
}
输入
5 2 6 1 3
输出
True

