2015-10-22 240 views
0

我正在學習二叉樹。我正在看斯坦福網站: 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是一個指向節點的指針嗎? 只需尋找一個簡單的修復程序即可打印左右節點。

+1

在紙上繪製結構,圓形作爲節點,指針作爲箭頭指向其他節點。 – Surt

回答

1
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 

你想要做的是打印左側和右側兒童中包含的數據。

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

test->left(*test).left其類型爲struct node*

要打印數據left需要

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

這是因爲 '左' & '右' 指針。

要打印出的左側或右側的 '數據',如下所示改變代碼:

COUT < < 「左」 < <測試 - >左>數據< < ENDL;

COUT < < 「右」 < <測試 - >右>數據< < ENDL;

但是,請注意,如果左側或右側爲NULL(即零),您可能會遇到內存訪問異常。

1

您可以正確打印「test-> data」,因爲這是一個int。問題是「test-> left」和「test-> right」是指針,而指針基本上是指另一個對象存儲位置的數字。

如果你想打印的左節點的數據,你不得不這樣做:

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

然後你就必須爲正確的節點做同樣的。