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.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its minimum depth = 2.
题目大意:
求出二叉树最小深度,深度被定义为从根节点到最近的叶节点的最短路径上的节点数。
解题思路:
遍历到根节点时判断全局的最小深度和当前深度的最小值。
/**
* 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 {
private:
int ans;
int helper(TreeNode *tmp, int deeper){
if(tmp->right==NULL&&tmp->left==NULL){
return ans==-1? deeper : min(deeper,ans);
}
if(tmp->left!=NULL){
ans = helper(tmp->left, deeper+1);
}
if(tmp->right!=NULL){
ans = helper(tmp->right, deeper+1);
}
return ans;
}
public:
int minDepth(TreeNode* root) {
ans= -1;
return root ? helper(root,1) : 0;
}
};