Can anyone point out a way of getting the depth of a Node in a Binary Tree (not a balanced one, or BST) without using recursion? Ideally in Java/C/C#
The no
Here is the most efficient solution I've come up with (C++). The trick is to use a second queue to store the children of all nodes at your current level. This will work for balanced and unbalanced binary trees.
template
struct TreeNode {
TreeNode* left_;
TreeNode* right_;
T* data_;
};
template
int find_depth( const TreeNode* root ) {
if ( root == NULL ) return 0;
int depth = 0;
std::queue*>* q1 = new std::queue*>;
std::queue*>* q2 = new std::queue*>;
q1->push( root );
while ( !q1->empty() ) {
// At the top of the outer loop q1 contains a complete horizontal level of the tree
depth++;
// Swap the queue pointers to avoid any deep copies
std::queue*>* tmpQ = q2;
q2 = q1;
q1 = tmpQ;
// Iterate over this level, inserting all children into q1
while( !q2->empty() ) {
const TreeNode* node = q2->front();
if ( node->left_ != NULL ) q1->push( node->left_ );
if ( node->right_ != NULL ) q1->push( node->right_ );
q2->pop();
}
}
delete q1;
delete q2;
return depth;
}