leetcode 110:平衡二叉树

直接选择用递归就可以了,因为需要求高度,所以需要求深度。

int maxDepth(TreeNode*root){
    if(root==NULL)return 0;
    TreeNode*l=root->left;
    TreeNode*r=root->right;
    return 1+std::max(maxDepth(l),maxDepth(r));
}

bool isBalanced(TreeNode*root){
    if(root==NULL)return true;
    TreeNode*l=root->left;
    TreeNode*r=root->right;
    if(std::abs(maxDepth(l)-maxDepth(r))>1)
        return false;
    else
        return isBalanced(l)&&isBalanced(r);
}

 

相关文章:

  • 2021-07-24
  • 2022-12-23
  • 2021-09-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-03
  • 2021-12-31
猜你喜欢
  • 2021-07-14
  • 2021-10-29
  • 2021-11-17
  • 2022-12-23
  • 2022-12-23
  • 2021-07-23
相关资源
相似解决方案