Amazon Interview Question
Software Engineer in Testsbob you forgot to increment the depth as you travel down the tree
plus, I think the question was meant to ask the height of a tree. Depth is usually for some node in the tree.
int getHeight(struct treeNode *tree) {
if(tree == NULL) {
return 0;
}
leftHeight = getHeight(tree->left);
rightHeight = getHeight(tree->right);
if(leftHeight > rightHeight) {
return (leftHeight+1);
}
else {
return (rightHeight+1);
}
}
If binary tree, its simple
int Height(Node *root)
{
if( !root ) return 0;
return 1 + max( Height(root->left), Height(root->right) );
}
int Max(int a, int b)
{
return (a > b)? a : b;
}
int finddepth(node* root)
- bob March 05, 2011{
if(root==null)
return 1;
depth=Max(finddepth(root->left),finddepth(root->right));
return depth;
}