I am trying to get the height of a BST using a stack. I was told that I should use preorder and measure find the largest size of the stack. However, this does not seem to work. Any ideas of what I am doing wrong.
int PBT::maxDepth() {
if (!root) {
return -1;
}
int depth=0;
stack<TreeNode *>s;
TreeNode * nodePtr=root;
for (; ; ) {
while (nodePtr) {
s.push(nodePtr);
if (s.size() > depth)
depth = s.size();
nodePtr=nodePtr->left;
}if (s.empty()) {
break;
}
nodePtr=s.top();
s.pop();
nodePtr=nodePtr->right;
}
return depth;
}