leetcode || 110、Balanced Binary Tree

本文深入探讨了平衡二叉树的概念及其判断方法,纠正了初学者易犯的误解,并通过递归算法实现了一个高效的判断过程。

problem:

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.

Hide Tags
  Tree Depth-first Search
题意:判断一棵二叉树是否为平衡二叉树

thinking:

(1)这道题以为很简单,但是仔细研究才发现,对平衡二叉树的理解有误:左右子树的最大深度(即树高)之差不超过1,

不是特指每个叶子节点的高度,是树的高度。我一开始是求出每个叶子节点的高度,再比较,这么做不符合平衡二叉树的定义

(2)准确思路是递归 每次对左右子树进行判断。

code:

错误思路:

class Solution {
    private:
        vector<int> depth;
    public:
       bool isBalanced(TreeNode *root) {
            if(root==NULL)
                return true;
            dfs(0,root);
           sort(depth.begin(),depth.end());
           if(*(depth.end()-1)-depth[0]>1)
               return false;
            
           else
               return true;
        }
    protected:
        void dfs(int dep,TreeNode *node)
        {
            if(node==NULL)
            {
                cout<<dep<<endl;
                depth.push_back(dep);
                return;
            }
            dep++;
            dfs(dep,node->left);
            dfs(dep,node->right);
        }
    };

正确答案:

class Solution {  
public:  
    bool isBalanced(TreeNode *root) {  
        int depth = 0;  
        return isbalance(root, depth);  
           
    }  
    bool isbalance(TreeNode *root, int &depth)  
    {  
        if(root == NULL)  
        {  
            depth = 0;  
            return true;  
        }  
        int ld,rd;  
        if( isbalance(root->left,ld) && isbalance(root->right,rd))  
        {  
            if( abs(ld - rd) > 1)  
            {  
                return false;  
            }  
            depth = ld > rd ? ld + 1 : rd + 1;  
            return true;  
        }  
    }  
       
       
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值