I am trying to do the LeetCode problem 111. Minimum Depth of Binary Tree:
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
My code runs, but doesn't change the minimum depth value at all. I've asked my classmates and a teacher, but they don't know why it won't work either. I've spent a lot of time trying to figure it out.
This is my code:
class Solution {
public:
int minHeight = 0, currHeight = 0;
int minDepth(TreeNode* root) {
searchTree(root);
return minHeight;
}
void searchTree(TreeNode* p) {
currHieght++;
if (p->right == nullptr && p->left == nullptr)
{
if (currHeight < minHeight) minHeight = currHeight--;
return;
}
else if (p->right == nullptr)
searchTree(p->left);
else if (p->left == nullptr)
searchTree(p->right);
else
{
searchTree(p->left);
searchTree(p->right);
currHeight--;
}
}
};
Whatever the input, my code always returns 0. What am I doing wrong?