Facebook Interview Question
Software Engineer / Developersthis is wrong soln as it goes only left-left-left and rht-rht-rht
i ve posted the right soln...
but where is the usage of binary search tree property
this is like the solution for binary tree
Iterative Approach. Recursion may be killing perf
// FindDepthOfABinaryTree.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
//using namespace stdadv;
class Node{
public:
int info;
Node* left;
Node* right;
Node(int info,Node* left, Node* right)
{
this->info = info;
this->left = left;
this->right = right;
}
};
Node* getTree()
{
Node * Root= new Node(5,new Node(6,new Node(8,NULL,new Node(10,NULL,NULL)),new Node(9,NULL,NULL)),new Node(7,new Node(8,NULL,NULL),new Node(9,NULL,NULL)));
return Root;
}
int getDepth(Node* root)
{
queue<Node*> q;
q.push(root);
int depth=-1;
Node * marker = root;
if(root== NULL)
{
return -1;
}else{
while(q.size()!=0)
{
//cout<<q.size();
/*The below is imp to note pop will not return value but front will*/
Node* gotNodeFromQueue= (Node*)q.front();
q.pop();
if(gotNodeFromQueue != root || depth == -1)
{
if(gotNodeFromQueue->left != NULL)
{
q.push(gotNodeFromQueue->left);
}
if(gotNodeFromQueue->right != NULL)
{
q.push(gotNodeFromQueue->right);
}
}
if(gotNodeFromQueue == root )
{
// We reached a marker and one level complete
depth++;
if(q.size() != 0)
q.push(root);
}
}
}
return depth;
}
int main()
{
Node * root = getTree();
int depth=getDepth(root);
cout<< "Depth:" << depth;
}
int btree::minheight(btreenode *k,queue q1,queue q2)
{
int h = -1;
q1.enqueue(k);
while(q1.front != -1)
{
btreenode* temp;
while(q1.front != -1)
q2.enqueue(q1.dequeue());
h++;
while(q2.front != -1)
{
temp = q2.dequeue();
if(temp -> leftchild != NULL)
{
q1.enqueue(temp -> leftchild);
}
else
{
cout << "Min height = " << h << endl;
system("pause");
exit(0);
}
if(temp -> rightchild != NULL)
{
q1.enqueue(temp -> rightchild);
}
else
{
cout << "Min height = " << h << endl;
system("pause");
exit(0);
}
}
}
return h;
}
Recursive approach:
int depthTree(Tree t) {
if(t==null || t.left==null || t.right==null)
}
#define MAX(x,y) ((x > y) ? x:y)
- Assange December 09, 2010int height(struct node *root)
{
if(root == null)
return 0;
ldepth = height(root->left) + 1;
rdepth = height(root->right) + 1;
return MAX(ldepth, rdepth);
}