题目:
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 binary tree
* 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)return 0;
int a=minDepth(root->right);
int b=minDepth(root->left);
if(a*b!=0)return min(a,b)+1;
else if(b==0)return a+1;
else if(a==0) return b+1;
}
};