104. 二叉树的深度

solution.h
#pragma once
#include <cstddef>

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
    int maxDepth(TreeNode* root);
};

二叉树的最大深度

#include "solition.h"
int Solution::maxDepth(TreeNode* root)
{
    if(root == NULL)
    {
        return NULL;
    }
    int left = maxDepth(root->left);
    int right = maxDepth(root->right);
    return (left > right) ? (left + 1) : (right + 1); 
}

二叉数的最小深度
第一种方法是分别算二叉树的宽度,然后比较求最宽

int Solution::minDepth(TreeNode* root)
{
    if (root == NULL)
    {
        return  false;
    }
    if(root->left == NULL && root->right == NULL);
    {
        return  1;
    }
    int left = minDepth(root->left);
    if (left == 0)
        left = INT_MAX;

    int rigth = minDepth(root->right);
    if (rigth == 0)
        rigth = INT_MAX;

    return  left < rigth ? left + 1 : rigth + 1;
}

第二种是判断那边是空的,如果是空的,则返回另一边的宽度

int Solution::minDepth2(TreeNode* root)
{
    if (root == nullptr)
    {
        return  0;
    }
    if (root->left == NULL)
        return minDepth2(root->right) + 1;
    if (root->right == NULL)
        return minDepth2(root->left) + 1;

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

推荐阅读更多精彩内容