Yahoo Interview Question
Software Engineer / Developersno recursion..probably..use graph traversal to count the number of nodes(=x) and take log()x or log(x)+1.
Do a level order traversal or BFS, and count the levels,
typedef struct node{
int data;
struct node *right;
struct node *left;
}Node;
typedef struct {
Node *p;
int level;
}queue;
void levelOrder(Node *ptr) {
if (ptr == NULL) return;
while(!isEmpty() ) {
queue *q = dequeue();
q->level++;
if (q->p->left != NULL) enqueue (q->p->left,q->level);
if (q->p->right != NULL) enqueue (q->p->right,q->level);
}
return ;
}
The depth of a tree is the length of the longest path from the root to any of the leaves.
- kay June 08, 2007So, the following recursive function should do when applied on root:
depth(inner_node) = max(
depth(inner_node->left_child),
depth(inner_node->right_child)
)
+ 1
and
depth(leaf) = 0