[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.

這題采用遞歸很簡單,但是要注意函數(shù)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;
}
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容