类似的再举一个例子:
题目:从上往下打印二叉树,何老师的代码如下(是没有问题的):
void PrintFromTopToBottom(BinaryTreeNode* pRoot)
{
if(pRoot == nullptr)
return;
std::deque<BinaryTreeNode *> dequeTreeNode;
dequeTreeNode.push_back(pRoot);
while(dequeTreeNode.size())
{
BinaryTreeNode *pNode = dequeTreeNode.front();
dequeTreeNode.pop_front();
printf("%d ", pNode->m_nValue);
if(pNode->m_pLeft)
dequeTreeNode.push_back(pNode->m_pLeft);
if(pNode->m_pRight)
dequeTreeNode.push_back(pNode->m_pRight);
}
}
deque::front返回值是引用(注:因为deque在堆上分配空间,所以可以返回引用。可参考:C++ 引用作为函数返回值)
但如将代码修改为:
void PrintFromTopToBottom(BinaryTreeNode* pRoot)
{
if (pRoot == nullptr)
return;
std::deque<BinaryTreeNode *> dequeTreeNode;
dequeTreeNode.push_back(pRoot);
while (dequeTreeNode.size())
{
BinaryTreeNode *&pNode = dequeTreeNode.front(); // 指针的引用
dequeTreeNode.pop_front();
printf("%d ", pNode->m_nValue);
if (pNode->m_pLeft)
dequeTreeNode.push_back(pNode->m_pLeft);
if (pNode->m_pRight)
dequeTreeNode.push_back(pNode->m_pRight);
}
}
因为pop_front()会析构,所以也会有问题,但可以修改为:
BinaryTreeNode *&pNode = dequeTreeNode.front(); // 指针的引用
printf("%d ", pNode->m_nValue);
dequeTreeNode.pop_front();
即先输出再析构。或者像何老师的代码那样(重新定义一个指针变量pNode,而不是指针引用):
BinaryTreeNode *pNode = dequeTreeNode.front();
dequeTreeNode.pop_front();
printf("%d ", pNode->m_nValue);