题目:
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.
解答:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
stack<TreeNode*> nodeStack;
stack<int> deptStack;
int curMinDepth = INT_MAX;
nodeStack.push(root);
deptStack.push(1);
while (!nodeStack.empty()) {
TreeNode* top = nodeStack.top();
int curDept = deptStack.top();
nodeStack.pop();
deptStack.pop();
if (top->left == NULL && top->right == NULL) {
curMinDepth = curMinDepth > curDept ? curDept : curMinDepth;
}
if (curDept < curMinDepth) {
if (top->left) {
nodeStack.push(top->left);
deptStack.push(curDept + 1);
}
if (top->right) {
nodeStack.push(top->right);
deptStack.push(curDept + 1);
}
}
}
return curMinDepth;
}
};