Balanced Binary Tree(平衡二叉树)

Given a binary tree, determine if it is height-balanced.(给定一棵二叉树,判断该树的高度是否平衡)

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.(在这里的高度平衡二叉树是指任意节点的两子树的深度差值不超过1)

1.个人分析
该问题的二叉树是否平衡的定义与AVL不一样,这里只要求二叉树的高度差不超过1即可,而不需要节点是有序的。
思路一:先序遍历二叉树,依次计算每个节点左右子树的高度,并判断高度差是否符合条件。
思路二:采用后序遍历,自底向上计算每个节点的左右子树高度差。

2.个人解法

int bTreeDepth(TreeNode *root)
{
    if(!root)   return 0;
    int left = bTreeDepth(root->left);
    int right = bTreeDepth(root->right);

    return left > right ? (left + 1) : (right + 1);
}

bool isBalanced(TreeNode* root) 
{
    if(!root) return true;

    int leftDepth = bTreeDepth(root->left);
    int rightDepth = bTreeDepth(root->right);
    int diff = leftDepth - rightDepth;
    if(diff < -1 || diff > 1)
        return false;

    return isBalanced(root->left) && isBalanced(root->right);
}

该解法的时间复杂度为O(nlogn),这里会有很多个节点被重复遍历,所以效率不高。

3.参考解法

bool isBalanced(TreeNode* root, int &depth)
{
    if(!root){
        depth = 0;
        return true;
    }

    int leftDepth, rightDepth;
    if(isBalanced(root->left, leftDepth) && isBalanced(root->right, rightDepth)){
        int diff = leftDepth - rightDepth;
        if(diff > 1 || diff < -1){
            depth = 1 + (leftDepth > rightDepth ? leftDepth : rightDepth);
            return false;
        }
    }

    return true;
}

bool isBalanced(TreeNode* root)
{
    int depth = 0;
    return isBalanced(root, depth);
}

该解法的时间复杂度为O(n),通过后序遍历,遍历一次每个节点并且返回当前高度。

4.总结
判断二叉树的递归解法主要有先序和后序两种遍历方式,上述的第一种比较直观和容易理解,而第二种则比较难设计和理解,但效率比较高。所以看得出程序效率的提升很大程度上依赖算法设计的复杂性。

PS:

  • 题目的中文翻译是本人所作,如有偏差敬请指正。
  • 其中的“个人分析”和“个人解法”均是本人最初的想法和做法,不一定是对的,只是作为一个对照和记录。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值