【题目描述】
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.
给定二叉树,求其最小深度。最小深度是从根节点到最近的叶节点沿最短路径的节点数。
【解题思路】
此题的常规思路是运用递归方法对二叉树进行广度优先遍历,先判断当前根节点是否为空,如果为空,直接返回当前值。否则,判断当前根节点是否有左子结点,没有,则遍历右子节点,递归值加1。如果当前根节点没有右子结点,则递归遍历左子结点,递归值加1。如果两个子结点都有,则返回两个递归函数值最小的那个加1。
【代码实现】
class Solution {
public:
int run(TreeNode *root) {
if(!root) return 0;
if(!root->left) return run(root->right)+1;
if(!root->right) return run(root->left)+1;
return 1+min(run(root->right),run(root->left));
}
};