0
点赞
收藏
分享

微信扫一扫

Leetcode110. 平衡二叉树

小美人鱼失去的腿 2022-03-25 阅读 58

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 条评论