【发布时间】:2017-09-24 02:20:29
【问题描述】:
正在尝试学习树节点...
Binary search tree (BST) is a binary tree where the value of each node is larger or equal to the values in all the nodes in that node's left subtree and is smaller than the values in all the nodes in that node's right subtree.
Write a function that checks if a given binary search tree contains a given value.
For example, for the following tree:
n1 (Value: 1, Left: null, Right: null)
n2 (Value: 2, Left: n1, Right: n3)
n3 (Value: 3, Left: null, Right: null)
Call to Contains(n2, 3) should return true since a tree with root at n2 contains number 3.
到目前为止,我得到了...
public class BinarySearchTree
{
public static bool Contains(Node root, int value)
{
foreach (var v in root)
{
if (root.Value == value)
{
//value found return true
}
}
}
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(Contains(n2, 3));
}
}
但 root 标记为不可用,如果我做 root。我得到了字符串、值、左、右的选项。
我不能像列表一样遍历节点吗? 如何检查是否在根目录中找到值? 谢谢
更新 啊,是的,好的...感谢 juharr 的回复,所以我已将代码更新为...
public static bool Contains(Node root, int value)
{
if (root.Value == value)
{
return true;
}
else if (root.Value > value)
{
if (root.Right == null)
{
Contains(root.Left, value);
}
Contains(root.Right, value);
}
else //(root.Value < value)
{
if (root.Left == null)
{
Contains(root.Right, value);
}
Contains(root.Left, value);
}
return false;
}
但是在第二个循环中,round root 为 null 并导致崩溃?
【问题讨论】:
-
你基本上需要检查值是否匹配,如果不匹配,则确定它是更大还是更小,并分别递归调用左侧或右侧节点上的方法。
-
感谢您的回复我试过了,请查看 OP 更新
-
如果
root == null怎么办? -
如果左侧或右侧是
null,则该值不存在,您无需检查另一个值。而是预先检查null。 -
当我再次调用 contains() 时,它只传递叶子而不是导致 null 的整个节点