【发布时间】:2015-11-13 20:35:27
【问题描述】:
我正在尝试找出这个程序是否可以检查二叉树是否是 BST,
以下是代码:
public static bool isValidBST(Node root)
{
return isValid(root, root.Left.Value,
root.Right.Value);
}
private static bool isValid(Node node, int MIN, int MAX)
{
// tree with no childres is BST
if (node == null)
return true;
if (node.Value <= MIN || node.Value >= MAX)
return false;
return isValid(node.Left, MIN, node.Value) && isValid(node.Right, node.Value, MAX);
}
我认为我的代码中缺少一些东西,例如,我认为此代码不适用于具有一个根和两个节点的树。你们能帮我修复我的实现吗?
我也在stackoverflow找到了这个解决方案
private static bool isValid(Node node, int MIN, int MAX)
{
// tree with no childres is BST
if (node == null)
return true;
if (node.Value > MIN && node.Value < MAX
&& isValid(node.Left, MIN, Math.Min(node.Value, MAX))
&& isValid(node.Right, Math.Max(node.Value, MIN), MAX))
return true;
else
return false;
}
但这对我不起作用!
这就是我尝试代码的方式:
public static void Main(string[] args)
{
Node n1 = new Node(1, null, null);
Node n3 = new Node(3, null, null);
Node n2 = new Node(2, n1, n3);
Console.WriteLine(isValidBST(n2));
Console.ReadLine();
}
结果是假的,而应该是真。
【问题讨论】:
-
那么当您在 1 节点树上运行该代码时会发生什么?你说你认为它行不通;但是您是否真的尝试过并看到会发生什么?
-
@Servy 是的,我做了兄弟,弄错了
-
当您调试程序并查看每个节点的验证方式时,哪些节点验证正确,哪些验证错误?
-
更好的问题是当你
use the Debugger并单步执行代码时会发生什么,你能找出你的逻辑缺陷发生在哪里吗..? -
如果您使用调试器step,您将看到返回
false的条件,然后在分析后您应该能够找到错误所在。
标签: c# algorithm binary-tree binary-search-tree