• 剑指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)

  • 相关阅读:
    UVA1599 理想路径 Ideal Path(最短路径)
    换根DP
    小w的魔术扑克(树状数组+并查集)
    NOIP 2016蚯蚓(优先队列)
    ZR 动物园
    T105017 seq(DP)
    noip2017酱油记
    noip2017酱油记前篇
    P1985 翻转棋
    luogu P2512 [HAOI2008]糖果传递
  • 原文地址:https://www.cnblogs.com/q1204675546/p/13488148.html
Copyright © 2020-2023  润新知