110. 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.

测试平衡二叉树是一个相当古老的问题了,调用递归分分钟解决,但是万万没想到,我居然犯了一个小小的错误,到时候time limited 上代码,大家可以参考一下,由于只提供一个isBalance函数,且返回的是bool值,所以我们需要另外一个函数来计算层高,如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int height(TreeNode* root)
    {
        int theheight=0;
        if(root == NULL)
        {
            return 0;
        }
        else
        {
           theheight=height(root->left)>height(root->right)?height(root->left)+1:height(root->right)+1;
           return theheight;
        }
    }

看的出来问题出现在那里么?没错,就是最长的这行,正是由于多次调用递归导致巨大的时间空间支出,进而转化为

     int height(TreeNode* root)
    {
        int theheight=0;
        if(root == NULL)
        {
            return 0;
        }
        else
        {
            int l=height(root->left);
            int r=height(root->right);
            theheight=l>r?l+1:r+1;
           return theheight;
        }
    }
接着使用isBalance 进行一下判断:

    bool isBalanced(TreeNode* root) {
        int leftheight,rightheight;
        if(root == NULL )
        {
            return true;
        }

        leftheight=root->left!=NULL?height(root->left)+1:0;

        rightheight=root->right!=NULL?height(root->right)+1:0;

        if((leftheight-rightheight)<=1 && isBalanced(root->left) && isBalanced(root->right)  )
        {
            return true;
        }
        else
        {
            return false;

        }




    }
accept后发现时间还是有点长,于是想到height函数在计算层高的时候就可以顺便把子树的balance状态统计了,于是。。。。

class Solution {
public:

    bool isBalanced(TreeNode* root) {

        int n=height(root);
        if(n<0)
        {
            return false;

        }
        else{
            return true;
        }



    }

public:   
    int height(TreeNode* root)
    {
        int theheight=0;
        
        if(root == NULL)
        {
            return 0;
        }
        else
        {
           int  r=height(root->right);
            int l=height(root->left);

           if(abs(r-l)<=1 && r!=-1 && l!=-1 )
           {
               theheight=r>l?r+1:l+1;
               return theheight;
           }
           else{

               return -1;
           }

        }


    }
};
但是此时啊,又出现了一个问题,我发现时间并没有提高很多,分明减少了一个递归,为何时间竟然不减少,眼尖的你们早就发现了 对不对,我多写了一个public,就是这个小小的public呀 在去掉之后,时间由原来的16ms变为12ms,飞跃啊,

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值