I've been stuck on this for some time now. This is what I have so far, but it gives the wrong result.
int get_min_height_iter(Node* r) {
if (!r) return 0;
std::queue<Node*> queue;
queue.push(r);
int count = 1;
while (!queue.empty()) {
Node* temp = queue.front();
queue.pop();
if (!temp->left || !temp->right)
return count;
++count;
queue.push(temp->left);
queue.push(temp->right);
}
return -1;
}
Note that I can already do this function using recursion, I'm specifically interested in using queue or a stack. I can also get maximum height of the tree; I now need to make a function to get the minimum height.
For example in this case, the function should return 3, but it's returning 2:
int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->right = new Node(4);
root->left->right->left = new Node(5);
root->right->right = new Node(6);
cout << get_min_height_iter(root);
cin.get();
}
I know why it's doing it, I traced the code using a debugger, but I don't have much experience with binary trees and I don't know how to fix it. A hint would be greatly appreciated!
countwith the node information as well. Otherwise, when you pop a node, you don't know what the depth was at the time when that node was added to the stack.root(1)->left(2)->left(empty)has a height of 2. However, as @jogojapan mentioned, this algorithm will not work well in other cases because you are not recording enough information.