Interview Question
Country: India
Interview Type: In-Person
class Node
{
public int Value { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
}
class Program
{
// 8
// / \
// 4 12
// / \ \
// 2 7 14
// / / \
// 5 13 15
static Node n15 = new Node { Value = 15, Left = null, Right = null };
static Node n13 = new Node { Value = 13, Left = null, Right = null };
static Node n14 = new Node { Value = 14, Left = n13, Right = n15 };
static Node n5 = new Node { Value = 5, Left = null, Right = null };
static Node n7 = new Node { Value = 7, Left = n5, Right = null };
static Node n2 = new Node { Value = 2, Left = null, Right = null };
static Node n12 = new Node { Value = 12, Left = null, Right = n14 };
static Node n4 = new Node { Value = 4, Left = n2, Right = n7 };
static Node root = new Node { Value = 8, Left = n4, Right = n12 };
static bool FindValue(int n, Node node)
{
if (null == node) return false;
if (n == node.Value) return true;
if (n >= node.Value)
{
return FindValue(n, node.Right);
}
else
{
return FindValue(n, node.Left);
}
}
static bool FindSum(int n)
{
for (int i=0; i<n/2; ++i)
{
int k = n - i;
if (true == FindValue(k, root) && true == FindValue(i, root)) return true;
}
return false;
}
static void Main()
{
//test
//Console.WriteLine(FindValue(4, root));
//Console.WriteLine(FindValue(7, root));
Console.WriteLine(FindSum(26));
}
}
- Chris August 24, 2016