美文网首页
104. 二叉树的深度

104. 二叉树的深度

作者: HITZGD | 来源:发表于2018-09-17 19:47 被阅读0次
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);
}

相关文章

网友评论

      本文标题:104. 二叉树的深度

      本文链接:https://www.haomeiwen.com/subject/seldnftx.html