Leetcode110. 平衡二叉树

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)

示例:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值