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

posted @ 2020-08-11 23:50  生活待我如初恋  阅读(162)  评论(0编辑  收藏  举报