【问题标题】:check a tree is balanced, why my code does not work?检查树是否平衡,为什么我的代码不起作用?
【发布时间】:2014-08-16 20:23:12
【问题描述】:
bool isBalanced(){
    bool balance = true;
    isBalanced(root, balance);
    return balance;
}
int isBalanced(Node* root, bool& balance){
    if (root == NULL) return 0;
    int left_height = 1 + height(root->left);
    int right_height = 1 + height(root->right);
    if (std::abs(left_height - right_height) > 1){
        balance = false;
    }
    return left_height > right_height ? left_height : right_height;
}

如果树不平衡,我希望 isBalanced() 将平衡设置为 false,但是当我运行它时,它无法正确检查树是否平衡,有人可以帮助我吗?谢谢

【问题讨论】:

  • 您甚至没有显示所有相关功能(例如,int height(Node*) 缺失),我们应该如何判断?
  • if 更改为if (std::abs(left_height - right_height) > 0)
  • 我发现我的错误是:将高度(root->left)更改为 isBalanced(root->left)。与 height(root->right) 相同。

标签: c++ tree balance


【解决方案1】:
bool isBalanced(Node *root)
{ 
   if(root == NULL)
         return true; 

   int left = height(root->left);
   int right= height(root->right);

   return abs(left - right) <= 1 && 
   isBalanced(root->left) &&
   isBalanced(root->right))
}

您也可以先查看stackoverflow,这可能会有所帮助。

【讨论】:

  • O(n^2) 时间复杂度,请查看问题后添加的我的答案。
【解决方案2】:

最后,我发现我可以修复它并使其成为 O(n) 时间和 O(logN) 空间复杂度

bool isBalanced(){
    if (isBalanced(root) == -1){
        return false;
}
    return true;
}
int isBalanced(Node* root){
    if (root == NULL) return 0;
    int left_height = 1 + isBalanced(root->left);
    if (left_height == -1){
        return -1;
    }
    int right_height = 1 + isBalanced(root->right);
    if (right_height == -1){
        return -1;
    }
    if (std::abs(left_height - right_height) > 1){
        return -1;
    }
    return left_height > right_height ? left_height : right_height;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 2013-02-15
    相关资源
    最近更新 更多