Every day a leetcode
题目来源:110. 平衡二叉树
平衡二叉树的定义是:二叉树的每个节点的左右子树的高度差的绝对值不超过 1 ,则二叉树是平衡二叉树。
根据定义,一棵二叉树是平衡二叉树,当且仅当其所有子树也都是平衡二叉树,因此可以使用递归的方式判断二叉树是不是平衡二叉树。
递归的顺序可以是自顶向下或者自底向上。
解法1:自顶向下递归
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int max(int a,int b)
{
return a>b?a:b;
}
int abs(int x)
{
return x>0?x:-x;
}
// 求树的深度
int Depth(struct TreeNode* root)
{
if(root == NULL) return 0;
return max(Depth(root->left),Depth(root->right))+1;
}
bool isBalanced(struct TreeNode* root){
// 访问到空节点或叶子节点,返回true
if(root == NULL) return true;
if(root->left == NULL && root->right == NULL) return true;
// 左右两个子树的高度差的绝对值超过1,不平衡,返回false
if(abs(Depth(root->left)-Depth(root->right))>1) return false;
// 递归判断root的左右子树
return isBalanced(root->left) && isBalanced(root->right);
}
结果:

复杂度分析:
时间复杂度:O(n)
空间复杂度: O(1)
解法2:自底向上递归
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int max(int a,int b)
{
return a>b?a:b;
}
int abs(int x)
{
return x>0?x:-x;
}
// 求树的深度
int Depth(struct TreeNode* root)
{
if(root == NULL) return 0;
int leftDepth=Depth(root->left);
int rightDepth=Depth(root->right);
if(leftDepth == -1 || rightDepth == -1) return -1;
if(abs(leftDepth-rightDepth)>1) return -1;
return max(leftDepth,rightDepth)+1;
}
bool isBalanced(struct TreeNode* root){
return Depth(root)>=0;
}
结果:

复杂度分析:
时间复杂度:O(n)
空间复杂度: O(1)
示例:











