Skip to content

111. Minimum Depth of Binary Tree

难度: Easy

刷题内容

原题连接 * https://leetcode-cn.com/problems/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.

Note: A leaf is a node with no children.

解题方案

思路 1

遍历树,找出最小深度的分支
void dfs(TreeNode* root, int depth, int& ans){
    if(root == NULL)
        return ;
    if(root->left==NULL && root->right==NULL){
        if(depth<ans)
            ans = depth;
        return;
    }
    dfs(root->left, depth+1, ans);
    dfs(root->right, depth+1, ans);
}
int minDepth(TreeNode* root) {
    int ans = 10000;
    if(root==NULL)
        return 0;
    dfs(root, 1, ans);
    return ans;
}



回到顶部