c++ 如何用NLR方法插入树的数据

7jmck4yq  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(106)

我有一个关于插入树的数据并通过NLR方法打印出来的C++代码。但是在插入数据之后,我不能使用菜单中的命令2打印树。
我知道这个问题是在“insertTree”的某个地方,但我不知道如何修复它

  1. struct node {
  2. int data;
  3. node* left;
  4. node* right;
  5. };
  6. void insertTree(node* t, int x) {
  7. //if the node to add is root
  8. if (t->data == NULL) {
  9. node* p = new node();
  10. p->data = x;
  11. p->left = NULL;
  12. p->right = NULL;
  13. t = p;
  14. }
  15. else {
  16. //if the added element is less than t
  17. if (t->data > x) {
  18. insertTree(t->left, x);//add the element to the left of t
  19. }
  20. else if(t->data < x) {
  21. insertTree(t->right, x);//add the element to the left of t
  22. }
  23. }
  24. }
  25. void duyet_NLR(node* t) {
  26. if (t->data != NULL) {
  27. cout << t->data << " ";
  28. duyet_NLR(t->left);
  29. duyet_NLR(t->right);
  30. system("pause");
  31. }
  32. }
lb3vh1jj

lb3vh1jj1#

程序中至少存在两个(或三个)大问题:

  • 所有检查if (t->data == NULL)if (t->data != NULL)的检查都是错误的。需要检查**t**是否为空指针。t->dataint,不应与NULL进行比较。另外,不要在C++中使用NULL。使用nullptr。在这种情况下,它会帮助您,因为如果您使用nullptr而不是NULL,程序将无法编译。
  • insertTree中的node*t是函数的本地值。您对它所做的任何更改对函数的调用者(即在menu中)都不可见。这可以通过引用指针来改变:
  1. void insertTree(node*& t, int x) // note a reference to the pointer
  • menu中也存在上述问题。当menu返回到main时,main中的指针仍然是空指针-所以你不能删除所有的节点。在这里做同样的修改:
  1. void menu(node*& t)

使用递归来插入节点可能不是问题,但是您可以通过在insertTree中循环找到插入点来避免这个问题。示例:

  1. void insertTree(node*& t, int x) {
  2. node** next = &t;
  3. while(*next) { // loop until a leaf node is found
  4. if((*next)->data > x) next = &(*next)->left;
  5. else if((*next)->data < x) next = &(*next)->right;
  6. // this value already exists in the tree
  7. else return;
  8. }
  9. // *next is here a null pointer so that's where we'll insert the new node
  10. *next = new node{x, nullptr, nullptr};
  11. }

Demo
您还需要添加一个函数来释放所有分配的内存。

展开查看全部

相关问题