C++ 二叉树打印节点

C++ Binary Tree Printing Nodes

我正在学习二叉树。我在看斯坦福网站: http://cslibrary.stanford.edu/110/BinaryTrees.html 有一道练习题,通过三次调用 newNode() 并使用三个指针变量来创建树。 给出了结构和新节点。我试图打印出节点。

struct node { 
    int data; 
    struct node* left; 
    struct node* right; 
} ;

/* 
 Helper function that allocates a new node 
 with the given data and NULL left and right pointers. 
*/ 
struct node* newNode(int data) { 
  struct node* node = new(struct node); 
  node->data = data; 
  node->left = NULL; 
  node->right = NULL;

  return(node); 
}; 

// call newNode() three times 
struct node* build123a() { 
  struct node* root = newNode(2); 
  struct node* lChild = newNode(1); 
  struct node* rChild = newNode(3);
  root->left = lChild; 
  root->right= rChild;

  return(root); 
}

int main() {

    struct node* test = build123a();
    cout << "root: " << test->data << endl;
    cout << "left: " << test->left << endl;
    cout << "right: " << test->right << endl;

    return 0;
}

问题是这只打印出根目录中的整数。 对于左右节点,它打印出地址位置。 我对指针的了解仍然有点不稳定。但是我只返回 root 应该没关系吧? newNode 是指向节点的指针吗? 只是寻找一个简单的修复来打印出左右节点。

test->left(*test).left 类型 struct node*

要打印 left 中的数据,您需要

cout << (test -> left -> data);

那是因为 'left' & 'right' 指针。

要打印出左边或右边的'data',修改代码如下:

cout << "left: " << test->left->data << endl;

cout << "right: " << test->right->data << endl;

但是请注意,如果 left 或 right 为 NULL(即零),您可能会遇到内存访问异常。

您可以正确打印 "test->data",因为它是一个整数。问题是 "test->left" 和 "test->right" 是指针,指针基本上是指代另一个对象存储位置的数字。

如果你想打印左节点的数据,你必须这样做:

cout << "left: " << test->left->data << endl;

然后您必须对正确的节点执行相同的操作。

struct node { 
    int data; // the actual data contained inside this node
    struct node* left; // a node pointer that points to the left child
    struct node* right; // a node pointer that points to the right child
};

struct node* test; // is a node pointer
test->left; // is a node pointer that points to the left child of test
test->right; // is a node pointer that points to the right child of test

cout << test->data; // prints the integer contained within the test node
cout << test->left; // prints the address of the left child of test since it's a pointer
cout << test->right; // prints the address of the right child of test since it's a pointer

你要做的是打印左右两边的数据children。

cout << test->left->data;
cout << test->right->data;