zoukankan      html  css  js  c++  java
  • 剑指office--------平衡二叉树

    平衡二叉树的性质:

          所有的节点的左右子树的深度差的绝对值不大于1

    题目描述

    输入一棵二叉树,判断该二叉树是否是平衡二叉树。
     
    在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
     
     
    思路1:比较裸的做法(每个节点都去比较左右子树的深度差的绝对值):
     1 class Solution {
     2 public:
     3     int CalDepth(TreeNode *pRoot){
     4         if (pRoot==nullptr)    return 0;
     5         
     6         return max(CalDepth(pRoot->left)+1,CalDepth(pRoot->right)+1);
     7     }
     8     bool IsBalanced_Solution(TreeNode* pRoot) {
     9         if (pRoot==nullptr)    return true;
    10         if (abs(CalDepth(pRoot->left)-CalDepth(pRoot->right))>1)
    11             return false;
    12         return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
    13     }
    14 };

    时间复杂度:O(n2

     空间复杂度:O(n)

    思路2:(自底向上)

     1 class Solution {
     2 public:
     3     bool IsBalanced_Solution(TreeNode* pRoot) {
     4         if (pRoot==nullptr)    return true;
     5         return CalDepth(pRoot)!=-1;
     6     }
     7     int CalDepth(TreeNode* pRoot){
     8         if (!pRoot)    return 0;
     9         int LeftDepth=CalDepth(pRoot->left);
    10         if (LeftDepth==-1)    return -1;
    11         int RightDepth=CalDepth(pRoot->right);
    12         if (RightDepth==-1)    return -1;
    13         if (abs(LeftDepth-RightDepth)>1)    return -1;
    14         return max(LeftDepth,RightDepth)+1;
    15     }
    16 };

    时间复杂度:O(N)
    空间复杂度:O(N)

  • 相关阅读:
    Lucene 基础理论
    .NET Micro Framework V4.2 QFE2新版本简介
    FlashPaper
    在django中实现QQ登录
    基于lucene的搜索服务器
    ASP.NET MVC的Razor引擎:RazorViewEngine
    .Net Micro Framework
    关于基于DDD+Event Sourcing设计的模型如何处理模型重构的问题的思考
    泛型
    Log4j源码分析及配置拓展
  • 原文地址:https://www.cnblogs.com/q1204675546/p/13488148.html
Copyright © 2011-2022 走看看