Consider a binary tree T. We define the path from the root to a leaf as the number of edges from the root to that leaf. The minimum path in a tree $T$ is the shortest path among all paths between the root and all leaves.

  • Write a function $\texttt{int min(T)}$ that returns the minimum path in the tree $T$.
  • Write a function $\texttt{int diff(T)}$ that returns the difference between the minimum and maximum paths in the tree $T$.
  • A binary tree $T$ is said to be \texttt{leftist} if, for each node $N$ in $T$, $\texttt{diff(left(N))}$ $\geq$ $\texttt{diff(right(N))}$. Write a function $\texttt{int leftest(T)}$ that determines if $T$ is leftist or not.

Difficulty level
This exercise is mostly suitable for students
int minT(Btree B)
{
    if(!B || !B->left && !B->right) return 0;
    return 1+min(minT(B->left), minT(B->right));
}

int maxT(Btree B)
{
    if(!B || !B->left && !B->right) return 0;
    return 1+max(maxT(B->left), maxT(B->right));
}

int diff(Btree B)
{
    return minT(B) - maxT(B);
}

int leftist(Btree B)
{
    if(!B || !B->left && !B->right) return 1;
    if(diff(B->left) < diff(B->right)) return 0;
    return leftist(B->left) && leftist(B->right);
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Left rotate an array