【问题标题】:C++ Binary Tree Printing NodesC++ 二叉树打印节点
【发布时间】: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


【解决方案1】:

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

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

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

然后你必须为正确的节点做同样的事情。

【讨论】:

    【解决方案2】:
    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;
    

    【讨论】:

      【解决方案3】:

      那是因为“左”和“右”指针。

      要打印出左边或右边的‘数据’,改代码如下:

      cout left->data

      cout right->data

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

      【讨论】:

        【解决方案4】:

        test-&gt;left(*test).left,其类型为 struct node*

        打印left中的数据需要

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

        【讨论】:

          猜你喜欢
          • 2012-04-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多