感谢您阅读我的主题。我正在测试圆顶中练习一点C#。我目前正在尝试编写的练习如下: http://www.testdome.com/Questions/Csharp/BinarySearchTree/484?testId=21&testDifficulty=Hard
我目前的结果:
你可以阅读我到目前为止写的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
public class Node
{
public int Value { get; set; } // Value of {node} == integer (1,2,3,4,5)
public Node Left { get; set; } // Reference to left node (n1, n2, n3) == Node.
public Node Right { get; set; } // Reference to right node (n1, n2, n3) == Node.
public Node(int value, Node left, Node right)
{
Value = value; // (int)
Left = left; // (node)
Right = right; // (node)
}
}
public class BinarySearchTree
{
public static bool IsValidBST(Node root)
{
if (root.Left == null && root.Right == null)
return true;
else if (root.Left == null)
{
// Checking root.Right.Value
if (root.Value <= root.Right.Value)
return true;
else
return false;
}
else if (root.Right == null)
{
// Checking root.Left.Value
if (root.Value > root.Left.Value)
return true;
else
return false;
}
else
{
// Checking both Values
if (root.Value > root.Left.Value && root.Value <= root.Right.Value)
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);
// Execute function and write it to the console
Console.WriteLine(IsValidBST(n2));
Console.ReadLine();
}
}
我不知道通过测试要实现什么。我不希望你给我书面代码,但更多关于运动的信息。请记住,我当前的代码远非整洁。谢谢大家。
答案 0 :(得分:2)
您没有检查所有上层节点值。你应该有所有上层节点的数组/列表,所以你可以检查它。
你也应该使用递归调用。 喜欢这个
IsValidBST(Node root, List<int> upperValues = null)
{
...
bool childIsValid = IsValidBST (root.Left, upperValuesLeft ) && IsValidBST(root.Right, upperValuesRight )
}
答案 1 :(得分:1)
您应该检查其他节点root.Left
和root.Right
,如果它们不是IsValidBST
则调用null
,然后检查这些结果。现在你只测试根节点而不是下降到树
答案 2 :(得分:1)
答案代码:
if (root.Value == value) return true;
if (root.Left != null && value < root.Value)
if (Contains(root.Left, value)) return true;
if (root.Right != null && value > root.Value)
if (Contains(root.Right, value)) return true;
return false;
阅读同一问题的my post。