【发布时间】:2016-01-22 09:09:00
【问题描述】:
我正在学习二叉树。我在看斯坦福的网站: http://cslibrary.stanford.edu/110/BinaryTrees.html 有一个实践问题是通过三次调用 newNode() 并使用三个指针变量来制作一棵树。 给出了 struct 和 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 是指向节点的指针吗? 只是寻找一个简单的修复来打印出左右节点。
【问题讨论】:
-
在纸上画出结构,用圆圈作为节点,用指针作为指向其他节点的箭头。
标签: c++ binary-tree