C++ 二叉树实现C++;

C++ 二叉树实现C++;,c++,tree,binary-tree,C++,Tree,Binary Tree,二叉树插入: #include "stdafx.h" #include <iostream> using namespace std; struct TreeNode { int value; TreeNode* left; TreeNode* right; }; struct TreeType { TreeNode* root; void insert(TreeNode* tree, int item); void insertItem(int v

二叉树插入:

#include "stdafx.h"
#include <iostream>

using namespace std;

struct TreeNode {
  int value;
  TreeNode* left;
  TreeNode* right;
};

struct TreeType {
  TreeNode* root;

  void insert(TreeNode* tree, int item);

  void insertItem(int value) {
    insert(root, value);
  }
};

void TreeType::insert(TreeNode* tree, int number) {
  if (tree == NULL) {
    tree = new TreeNode;
    tree->left = NULL;
    tree->right = NULL;
    tree->value = number;
    cout << "DONE";
  } else if (number < tree->value) {
    insert(tree->left, number);
  } else {
    insert(tree->right, number);
  }
}

int main() {
  TreeType* MyTree = new TreeType;
  MyTree->insertItem(8);

  return 0;
}
#包括“stdafx.h”
#包括
使用名称空间std;
树状结构{
int值;
TreeNode*左;
TreeNode*对;
};
结构树型{
树根;
无效插入(树节点*树,整数项);
无效插入项(int值){
插入(根,值);
}
};
void TreeType::insert(TreeNode*tree,整数){
if(tree==NULL){
树=新树节点;
树->左=空;
树->右=空;
树->值=数量;
cout值){
插入(树->左,编号);
}否则{
插入(树->右侧,编号);
}
}
int main(){
树型*MyTree=新树型;
MyTree->insertItem(8);
返回0;
}

我目前正在学习C++中的数据结构,这是在二进制树中插入的代码。 编译之后,一切看起来都很好,但是当我试图执行这个程序时,它崩溃了


有人能告诉我哪里错了吗?

在树型构造函数中,我认为应该显式地将root point设置为NULL

TreeType::TreeType() {
  root = NULL;
}

试试这样的-

 struct Node {
    int Data;
    Node* Left;
    Node* Right; 
};

Node* Find( Node* node, int value )
{
    if( node == NULL )
        return NULL;
    if( node->Data == value )
        return node;
    if( node->Data > value )
        return Find( node->Left, value );
    else
        return Find( node->Right, value );
};

void Insert( Node* node, int value )
{
    if( node == NULL ) {
        node = new Node( value );
        return;
    }
    if( node->Data > value )
        Insert( node->Left, value );
    else
        Insert( node->Right, value );
};

在树构造函数中,需要将根指针初始化为NULL。不能保证将其初始化为NULL

在linux中编译时,可以使用gdb显示SEGFULT的来源

其他一些注意事项:

  • 在分配新节点后,应该将值重新分配给<代码>根>代码。您没有这样做,因为您缺少了C++的一个基本原理。也就是说,它是基于C的,而C的事情是严格的“按值”。函数/方法调用范例。因此,函数调用中的所有参数都是按值进行的。当您传入root的内存地址时,实际上是在复制指针的值。然后,您只需更新本地值。您需要将其分配回root。如果您想前后学习这个概念,我强烈建议您观看
  • 在main函数中,您应该尝试将符号名称保持为小写而不是CamelCase。这有助于区分变量和类型(类型应保持CamelCase)
  • 在TreeType::insert方法中,应该调用变量tree_节点而不是tree。这样做有助于反映正确的类型并避免混淆
  • 只要有可能,尝试使用
    this->root
    this->insert
    符号。如果您意外地创建了一个局部范围的
    root
    变量,它不仅可以正确解决问题,而且对于定义数据或方法的读者来说,它也更清晰。伟大的编码是关于通信的。可能只需要100-500毫秒让读者理解符号指向何处;然而,你在避免歧义方面所能节省的一点钱,加在一起,就形成了一个更清晰的软件。你未来的自己(和你的同事)会感谢你的。参见

  • 最后,我不能夸大从源头学习的重要性。如果你第一次学习C或C++,它会节省你几个小时、几个小时、几个小时。在从源代码中学习之后,编程也会更愉快,因为你能理解很多概念。事实上,事情是这样的。当你有足够的能力时,你会觉得更有趣。

    你是否尝试过使用调试器和/或valgrind?你应该使用“void Insert(Node**Node,int-value)”,否则你无法创建根节点。。。