题解 | #判断是不是平衡二叉树#

判断是不是平衡二叉树

http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222

递归一直是弱项

class Solution {
  public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
      return deepth(pRoot) != -1;
    }
  private:
    int deepth(TreeNode *root) {
      if (root == nullptr) {
        return 0;
      }
      
      int ldep = deepth(root->left);
      if (ldep == -1) {
        return -1;
      }
      
      int rdep = deepth(root->right);
      if (rdep == -1) {
        return -1;
      }
      
      int sub = std::abs(ldep - rdep);
      
      //  -1会一直向上传递
      if (sub > 1) {
        return -1;
      }
      
      return std::max(ldep, rdep) + 1;
    }
};
全部评论

相关推荐

2025-12-15 14:25
云南大学 Java
lei22:入职可能会看学信网,最好别伪装,这个简历找实习肯定是够的,肯定会有收 28 届实习生的公司的,多投就行
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务