题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
牛客链接:
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=13&&tqId=11192&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
解题思路:
有两种思路:
第一种,计算出每个节点的高度,左右高度进行比较,若大于1,则不是平衡二叉树,但会存在重复遍历节点的情况
第二种:用后序遍历的方式遍历二叉树,在遍历一个节点之前已经遍历了左右子树。在遍历每个节点的时候记录它的深度。每个节点只会遍历一次。
代码一
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if (pRoot == NULL) return true;
int left = treeDepth(pRoot->left);
int right = treeDepth(pRoot->right);
if(right-left>1 || left-right>1) {
return false;
}
return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
}
int treeDepth(TreeNode* pRoot) {
if (pRoot == NULL) return 0;
return 1+max(treeDepth(pRoot->left),treeDepth(pRoot->right));
}
};
代码二:
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth = 0;
return isBalanced(pRoot, &depth);
}
bool isBalanced(TreeNode* pRoot, int* depth) {
if(pRoot == NULL) {
*depth = 0;
return true;
}
int left, right;
if(isBalanced(pRoot->right, &right)&&isBalanced(pRoot->left, &left)) {
int diff = left-right;
if(diff>=-1 && diff<=1) {
*depth = right>left ? right+1:left+1;
return true;
}
}
return false;
}
};
注意:
平衡二叉树
(Balanced Binary Tree)又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
参考链接:
https://www.cnblogs.com/zhangbaochong/p/5164994.html