Leetcode:二叉树的最大深度

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

自己设计的代码:

下面的代码是可以正常运行的但是leetcode跑不过。

设计思路:

递归返回条件1:遍历到空节点

递归返回条件2:遍历到的节点为叶子节点

只要有子节点的节点都会进行递归,只要进行了递归count这个全局变量的值就会增加1。

注意:

①加1的前提是在左右节点都递归完毕后进行

②全局变量只加不减,所以不需要进行比较

static int count = 1;

int maxDepth(struct TreeNode* root){

    if(root==NULL)

    {

        return; 

    }

    else if((root->left==NULL)&&(root->right==NULL))

    {

        return;

    }

    else

    {

        maxDepth(root->right);

        maxDepth(root->left);

        count++;

    }

    return count;

}

网上优秀代码:

代码解析:

①设计了一个GetMaxDepth函数,通过传参记录深度值,避免变量出现的一系列覆盖等问题,值得借鉴

②return MyMax(GetMaxDepth(root->left, d),GetMaxDepth(root->right,d))这种形式的代码底层非常多见,清晰准确明了。

int MyMax(int a, int b){

    if(a>b){

        return a;

    }

    return b;

}

int GetMaxDepth(struct TreeNode *root, int d){

    if (root == NULL)

    {

        return d;

    }

    d++;

    return MyMax(GetMaxDepth(root->left, d),GetMaxDepth(root->right,d));

}

int maxDepth(struct TreeNode* root){

    return GetMaxDepth(root, 0);

}

官方代码:深度优先搜索 DFS

八股样板

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == nullptr) return 0;
        return max(maxDepth(root->left), maxDepth(root->right)) + 1;
    }
};

广度优先搜索

略(未研究)

posted @ 2023-06-14 23:43  日暮_途远  阅读(3)  评论(0)    收藏  举报  来源