c++ - LinkedList ADT指针 block

标签 c++ list pointers tree nodes

我正在为我的 compsci 类实现许多 LinkedList ADT,但我在每个类上都遇到了同样的问题。下面列出的代码是一个二叉树 ADT。尝试将数据输入新节点时,编译器会丢失。代码编译没有任何错误,但编译器没有返回任何东西,我认为它在尝试找到指针时卡住了。我来自 Java,所以我仍在研究指针。

#include <iostream>
struct TreeNode {
  //represents a single node in a binary tree of int data
  int data; //immediate data
  TreeNode *left; //left subtree
  TreeNode *right; //right subtree
  TreeNode(int in);
};

TreeNode::TreeNode(int in) {
  data = in;
  left = NULL;
  right = NULL;
}

编译器似乎无法找到这两个附加函数中引用的指针。

void addLeft(TreeNode *root, int newData) {
  TreeNode *new_node;
  new_node->data = newData;
  root->left = new_node;
}
void addRight(TreeNode *root, int newData) {
  TreeNode *new_node;
  new_node->data = newData;
  root->right = new_node;
}
//counts nodes in binary tree from designated root point
int countNodes(TreeNode *root) {
  if (!root) {
    return 0; //empty tree
  }
  int count = 1;
  count += countNodes(root->left); //adds left subtree nodes
  count += countNodes(root->right); //adds right subtree countNodes
  return count;
}
void preorderPrint(TreeNode *root) { //root first, then left, then right
  if (root) {
    std::cout << root->data << " ";
    preorderPrint(root->left);
    preorderPrint(root->right);
  }
}

void postorderPrint(TreeNode *root) { //left first, then right, then root
  if (root) {
    postorderPrint(root->left);
    postorderPrint(root->right);
    std::cout << root->data << " ";
  }
}
void inorderPrint(TreeNode *root) { //left first, then root, then right
  if (root) {
    inorderPrint(root->left);
    std::cout << root->data << " ";
    inorderPrint(root->right);
  }
}
bool tree_contains(TreeNode *root, int item) {
  if (!root) {
    return false; //if the root doesn't exist, the tree doesn't exist
  }
  else if (root->data = item) {
    return true; //item is found in the root node
  }
  else if (root->data > item) {

  }
}

int main() {
  TreeNode *root;
  root->data = 5;
  addLeft(root, 4);
  addRight(root,9);
  inorderPrint(root);
  return 0;
}

最佳答案

您的root 未初始化。它目前有一个未定义的值。应该是:

TreeNode *root = new TreeNode(5);
... // Do whatever you want
// delete root and everything else.

关于c++ - LinkedList ADT指针 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53455536/

相关文章:

C++ std::async 在主线程上运行

c++ - 如何遍历 std::index_sequence

c++ - 如何将结构作为指针传递? [C++]

c++ - "proper"使用 OpenGL 的行星围绕太阳的椭圆轨道

python - 如何让我的程序随机列出列表中的每个项目并且只列出一次

Java 彩票游戏

Python - 在和不在列表语法错误中

c - 将节点添加到链表时堆损坏

c - 指针及其取消引用的方法

c++ - Container end() 迭代器如何在(例如)Container 大小变化时演变