freemandj
2021-03-20 17:34
采纳率: 63.2%
浏览 33

关于二叉排序树,输不出任何结果,C++,求解答Dev

 #include<iostream>
#include<string>
#include<vector>

#include<algorithm>
using namespace std;

class TreeNode
{
public:
    int data;
    TreeNode *left, *right;
    TreeNode() {
    left = right = NULL;
    data=0;
     }
};
class BSTree
{
public:
    TreeNode *root;

    BSTree() { root = NULL; }
    void AddintoTree(int num)
    {
        TreeNode *t = root;
        while (true)
        {
            if (num < t->data)
            {
                if (t->left == NULL)
                {
                    t->left = new TreeNode;
                    t->left->data = num;
                    return;
                }
                else
                {
                    t = t->left;
                }
            }
            else
            {
                if (t->right == NULL)
                {
                    t->right = new TreeNode;
                    t->right->data = num;
                    return;
                }
                else
                {
                    t = t->right;
                }
            }
        }
    }
    void Preorder(TreeNode *root, vector<int> &ans) //递归前序
{
    if (root == NULL)
        return;

    ans.push_back(root->data);
    Preorder(root->left, ans);
    Preorder(root->right, ans);
}
void Inorder(TreeNode *root, vector<int> &ans) //递归中序
{
    if (root == NULL)
        return;

    Inorder(root->left, ans);
    ans.push_back(root->data);
    Inorder(root->right, ans);
}

void Postorder(TreeNode *root, vector<int> &ans) //递归后序
{
    if (root == NULL)
        return;

    Postorder(root->left, ans);
    Postorder(root->right, ans);
    ans.push_back(root->data);
}
TreeNode *search(int value){
    TreeNode *p=root;
    while(p!=NULL||p->data==value){
    if(value<p->data){
        p=p->left;
    }    
    else{
        p=p->right;
    }    
    }
    return p;
}
TreeNode *findmax(){
    TreeNode *p=root;
    while(p!=NULL){
        p=p->left;
    }
    return p;
}

};
int main(){
    BSTree bstree;
    bstree.AddintoTree(1);
     bstree.AddintoTree(2);
          bstree.AddintoTree(9);
               bstree.AddintoTree(7);
                    bstree.AddintoTree(8);
                         bstree.AddintoTree(4);
                   
    vector<int> ans;
    bstree.Inorder(bstree.root,ans);
    vector<int>:: iterator it;
    for(it=ans.begin();it!=ans.end();it++){
        cout<<*it;
    }
    TreeNode *treenode;
    treenode=bstree.findmax();
    cout<<treenode->data;
    
}

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • cpp_learner 2021-03-20 17:46
    已采纳

    BSTree类,AddintoTree函数,root都还没分配内存,你就在main函数里进行调用了。此时root为NULL,你还使用它,就报错了。

    1 打赏 评论

相关推荐 更多相似问题