Binary tree (count nodes) interview question
Given a LEFT and a RIGHT property that returns the underlying LEFT tree and the underlying RIGHT tree respectively, find the total count of the nodes in the tree.
class BinaryTree<T>
{
private BinaryTree<T> left; private BinaryTree<T> right;
public int CountNodes<T>(this IBinaryTree<T> tree) { // TODO: What goes here? }
}
Solution
public int CountNodes<T>(this IBinaryTree<T> t)
{
return 1 + t.left.CountNodes() + t.right.CountNodes();
}
Leave a Reply