剑指offer 面试题55 - II. 平衡二叉树 难度 简单 17 收藏 分享

我的解题:

1.每个节点都需要重复求高度

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(!root)   return true;
        if(isBalanced(root->left)&&isBalanced(root->right)
        &&abs(func(root->left)-func(root->right))<=1) return true;
        else    return false;
    }
    int func(TreeNode* root){
        if(!root)   return 0;
        return max(func(root->left),func(root->right))+1;
    }
};

2. 

class Solution {
public:
    bool flag=true;
    bool isBalanced(TreeNode* root) {
        func(root);
        return flag;
    }
    int func(TreeNode* root){
        if(!root)   return 0;
        int l=func(root->left);
        int r=func(root->right);
        if(abs(l-r)>1)   flag=false;
        return max(l,r)+1;
    }
};

咦,这为啥还不如上一种呢?

发布了76 篇原创文章 · 获赞 1 · 访问量 584

猜你喜欢

转载自blog.csdn.net/qq_41041762/article/details/105588434