【发布时间】:2014-12-03 20:52:44
【问题描述】:
我正在尝试用 C++ 编写一些数据结构硬件。当我尝试使用队列构造二叉树时,不知何故被指针问题弄糊涂了。
class Tree{
private:
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};
public:
TreeNode* root = NULL;
Tree();
Tree(queue<int>& val);
~Tree();
string toString_bf();
};
Tree(queue<int> &vals){
if (vals.empty())
return;
root = new TreeNode(vals.front());
vals.pop();
queue<TreeNode**> pts; // what is the meaning of this? Why should use pointers to pointer?
pts.push(&(root->left)); // also have doubts here, about the reference used in the parameter
pts.push(&(root->right));
while (!vals.empty()){
TreeNode* t = new TreeNode(vals.front());
*(pts.front()) = t; // and here
pts.pop();
vals.pop();
pts.push(&(t->left));
pts.push(&(t->right));
}
}
按照我的理解,left和right都是指针,为什么不能直接传值呢?
【问题讨论】:
标签: c++ pointers data-structures