[leetcode-111]Minimum Depth of Binary Tree(C语言)

问题描述:
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 a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int findDepth(struct TreeNode* root,int step){
    if(root->left==NULL&&root->right == NULL)
        return step+1;
    int leftStep = 0;
    int rightStep = 0;
    if(root->left)
        leftStep = findDepth(root->left,step+1);
    if(root->right)
        rightStep = findDepth(root->right,step+1);

    if(leftStep == 0)
        return rightStep;
    else if(rightStep == 0)
        return leftStep;
    else
        return (leftStep<rightStep)?leftStep:rightStep;
}
int minDepth(struct TreeNode* root) {
    if(!root)
        return 0;

    return findDepth(root,0);
}
阅读更多
文章标签: leetcode 算法
个人分类: leetcode
上一篇[leetcode-54]Spiral Matrix(C语言)
下一篇[leetcode91]Restore IP Addresses(java)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭