sdu_2017_XY
sdu_2017_XY
2018-12-09 14:46

对于实现一个树是否为平衡树的问题

5
  • struct
  • binarytree

我认为编写的函数没什么问题,应该是main函数的问题,求大神们指教。

#include <iostream>
using namespace std; 
struct TreeNode{
    TreeNode* left;
    TreeNode* right;
    int data;
};
int Height(TreeNode* root)
{
    if (root==NULL)
        return 0;

    //遇到叶子结点就返回
    if (root->left == NULL && root->right == NULL)
        return 1;

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

    return (left) > right ? (left + 1) : (right + 1);
}
bool IsBalanced(TreeNode* root)
{
    if (root == NULL)
        return true;

    int left = Height(root->left);
    int right = Height(root->right);
    int diff = left - right;  //左右高度差

    if (diff > 1 || diff < -1)  
        return false;

    return IsBalanced(root->left) && IsBalanced(root->right);
}
int main(int argc, char** argv) {
    TreeNode *root,*left2,*right2,*left3,*left4;
    //root->left=left2;
//  root->right=right2;
//  left2->left=left3;
    //left3->left=left4;
    cout<<IsBalanced(root);
    return 0;
}

Process exited after 4.007 seconds with return value 3221225477
请按任意键继续. . .

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答

为你推荐