努力學習樹節點...二叉搜索樹找到,如果值存在
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.
到目前爲止IV得了......
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));
}
}
但根標記爲不可用,如果我做根。我得到選項tostring,value,left,right。
我不能像列表那樣遍歷節點嗎? 如何檢查在根中是否有值? 謝謝
UPDATE 稀釋是OK ...感謝您的答覆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;
}
但是在第二輪循環根null並導致崩潰?
您基本上需要檢查值是否匹配,如果不確定它是大還是小,並分別遞歸調用左側或右側節點上的方法。 – juharr
感謝您的回覆我試過這個請參閱OP – John
上的更新如果'root == null'怎麼辦? –