【问题标题】:How to work with binary tree in C++?如何在 C++ 中使用二叉树?
【发布时间】:2018-10-11 12:33:15
【问题描述】:

我有一个程序,其中我有一个二叉树,表示为具有两个指针和一个根的结构。然后我想输入 n 个元素(由 br 变量表示)作为树节点的值。然后我使用add(param1,...) 函数输入这些元素。但是,当我按回车键时,在我输入所有这些后,程序就会崩溃。我想问一下为什么会这样?

// TreeGraph.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;
struct elem {
    char key;
    elem *left, *right;
} *root = NULL;
void add(int n, elem * &t);
int num,br,i;
int main()
{
    cout << "Въведете брой елементи\n";
    cin >> br;
    cout << "Въведете стойнсотите на листата на дървото\n";
    while (i != br) {
    cin >> num;
    add(num, root);
    i++;
    }
    return 0;
}
void add(int n, elem * &t) {
    if (t) {
        t = new elem;
        t->key = n;
        t->left = t->right = NULL;
    }
    else {
        if (t->key < n)
            add(n, t->right);
        else
            add(n, t->left);
    }
}

【问题讨论】:

  • @Asesh • i 是一个全局变量,因此它被初始化为零。
  • 另一个与问题无关的问题是 elem 有char key,但 add 使用的是int n。可能应该将 elem 更改为 int key

标签: c++ pointers binary-tree add


【解决方案1】:

问题不是无限循环。您正在取消引用一个空指针,因此程序崩溃了。

在这段代码中:

void add(int n, elem * &t) {
    if (t) {
        t = new elem;
        t->key = n;
        t->left = t->right = NULL;
    }
    else {
        if (t->key < n)
            add(n, t->right);
        else
            add(n, t->left);
    }
}

您添加节点的条件不正确。应该是if (!t)。二叉搜索树中新节点的位置必须是具有至少一个空子指针的节点的子节点。要添加节点,您需要递归到这些空指针之一,然后将节点添加到那里。

想一想当您将初始为空的根传递给add 函数时会发生什么。第一个if 语句中的条件为假,因此当您尝试检查条件if (t-&gt;key &lt; n) 时,您正在尝试访问不存在对象的key 字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 2021-12-04
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多