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.

当递归到叶子结点时,无左子结点和右子结点,根据if语句,会继续递归其右子结点,进而检测到当前结点为空,递归终止。

class Solution {
public:
    int run(TreeNode *root) {
        if(root==NULL)
            return 0;
        else if((root->left!=NULL)&&(root->right!=NULL)){
            int Left=run(root->left)+1;
            int Right=run(root->right)+1;
            return Left>Right?Right:Left;
        }else if(root->left!=NULL){
            return run(root->left)+1;
        }else{
            return run(root->right)+1;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/zslngu/article/details/80494749