栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

树的专题三

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

树的专题三

树的最大深度

104. 二叉树的最大深度 - 力扣(LeetCode) (leetcode-cn.com)

class Solution {
public:
    int getDepth(TreeNode* node)
    {
       if(node==NULL)  return 0;
       int leftDepth = getDepth(node->left);
       int rightDepth = getDepth(node->right);
       int depth = 1 + max(leftDepth,rightDepth);//包含当前中间节点就算了最深深度总和
       return depth;
    }

    int maxDepth(TreeNode* root) {
     return getDepth(root);
    }
};
二叉树最小深度

、111. 二叉树的最小深度 - 力扣(LeetCode) (leetcode-cn.com)

//这道题和最大深度不同的一点在于:
//最小深度在于是:根节点到最近叶子结点的最短路径上的节点数量。
//也就是说左右孩子都为空的结点才是“目的地”
//如果照搬最大深度的代码,会造成让左孩子为空的情况下算为叶子结点而直接得出错误的答案
class Solution {
public:
    int getDepth(TreeNode* node){
    if(node==NULL)       return 0;
    int leftDepth = getDepth(node->left);
    int rightDepth = getDepth(node->right);

    if(node->left == NULL && node->right != NULL)
    {
        return 1+rightDepth;
    }
    if(node->right ==NULL && node->left !=NULL)
    {
        return 1+leftDepth;
    }
     return 1 + min(leftDepth,rightDepth);
    }
    int minDepth(TreeNode* root) {
      return getDepth(root);
    }
};

平衡二叉树

110. 平衡二叉树 - 力扣(LeetCode) (leetcode-cn.com)

class Solution {
//这道题的思路在于平衡二叉树节点的左孩子和右孩子高度不能超过一
public:
    // 返回以该节点为根节点的二叉树的高度,如果不是二叉搜索树了则返回-1
    int getDepth(TreeNode* node) {
        if (node == NULL)   return 0;
        int leftDepth = getDepth(node->left);
        if (leftDepth == -1) return -1;
        int rightDepth = getDepth(node->right);
        if (rightDepth == -1) return -1;
        return abs(leftDepth - rightDepth) > 1 ? -1 : 1 + max(leftDepth, rightDepth);
    }
    bool isBalanced(TreeNode* root) {
        return getDepth(root) == -1 ? false : true;
    }
};

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/779352.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号