C++ 二叉树打印节点

标签 c++ binary-tree

我正在学习二叉树。我在看斯坦福网站: 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 是指向节点的指针吗? 只是寻找一个简单的修复来打印出左右节点。

最佳答案

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

你想要做的是打印左右 child 中包含的数据。

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

关于C++ 二叉树打印节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33292026/

相关文章:

c - 二叉搜索树输出文件不是预期的输出数据

python - 递归解析树的所有级别

algorithm - 来自两个未排序数组的 BST

返回二叉树中最短分支长度的算法

c++ - 如何在C++中创建指针数组

c++ - 如果条件不满足时触发语句?

c++ - 将C union 转换为C++ union

c++ - Linux:作为共享对象 API 的 C++ 抽象类

c++ - 将 'const' 添加到指针可以帮助优化吗?

tree - 如何让隐形节点在graphviz中占据空间?