我正在學習二叉樹。我正在看斯坦福網站: http://cslibrary.stanford.edu/110/BinaryTrees.html 有一個練習問題,通過調用newNode()三次並使用三個指針變量來生成樹。 給出了struct和newNode。我試圖打印出節點。C++二叉樹打印節點
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是一個指向節點的指針嗎? 只需尋找一個簡單的修復程序即可打印左右節點。
在紙上繪製結構,圓形作爲節點,指針作爲箭頭指向其他節點。 – Surt