[LeetCode]111. 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.

这题采用递归很简单,但是要注意函数minDepth()最后的return,要像如下这样写

int lDepth = minDepth(root->left);
int rDepth = minDepth(root->right);
return min(lDepth, rDepth)+1;

不能写为

return min(minDepth(root->left), minDepth(root->right))+1;

否则会导致time exceeded,因为min(A,B)会进行宏替换,导致minDepth(root->left)和minDepth(root->right)都被算了2遍

C代码
#include <stdlib.h>
#include <assert.h>

#define min(A,B) ((A)<(B)?(A):(B))

struct TreeNode {
    int val;
    struct TreeNode* left;
    struct TreeNode* right;
};

int minDepth(struct TreeNode* root) {
    if(root == NULL)
        return 0;
    if(root->left == NULL)
        return minDepth(root->right)+1;
    if(root->right == NULL)
        return minDepth(root->left)+1;

    int lDepth = minDepth(root->left);
    int rDepth = minDepth(root->right);
    return min(lDepth, rDepth)+1;
}

int main() {
    struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode*));
    root->val = 1;
    struct TreeNode* left = (struct TreeNode*)malloc(sizeof(struct TreeNode*));
    left->val = 2;
    root->left = left;
    root->right = NULL;
    left->left = NULL;
    left->right = NULL;

    assert(minDepth(root) == 2);

    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容