我有以下功能打印树,以便正常工作:
void PrintInOrder(TTreeNode const * const pRoot) {
if (pRoot != 0) {
PrintInOrder(pRoot->pLeft);
if(pRoot->pLeft) std::cout << ",";
std::cout << pRoot->Data;
if(pRoot->pRight) std::cout << ",";
PrintInOrder(pRoot->pRight);
}
}
这是我的预订打印功能:
void PrintPreOrder(TTreeNode const * const pRoot) {
if (pRoot != 0) {
std::cout << pRoot->Data << std::endl;
PrintPreOrder(pRoot->pLeft);
PrintPreOrder(pRoot->pRight);
}
}
因为我太愚蠢了解如何将它打印出来,就像inorder函数一样分开,我希望你们可以帮助我!
谢谢!
更新
预订功能现在有效,这是正确的后序功能吗?
void PrintPostOrder(TTreeNode const * const pRoot) {
if (pRoot != 0) {
PrintPostOrder(pRoot->pLeft);
if(pRoot->pLeft) std::cout << ",";
PrintPostOrder(pRoot->pRight);
if(pRoot->pRight) std::cout << ",";
std::cout << pRoot->Data;
}
}
答案 0 :(得分:1)
void PrintPreOrder(TTreeNode const * const pRoot) {
if (pRoot != 0) {
std::cout << pRoot->Data << std::endl;
if(pRoot->pLeft || pRoot->pRight) std::cout << ",";
PrintPreOrder(pRoot->pLeft);
if(pRoot->pLeft && pRoot->pRight) std::cout << ",";
PrintPreOrder(pRoot->pRight);
}
}
另请注意,这将按预先遍历打印树。
答案 1 :(得分:1)
这是正确的方法:
void PrintPreOrder(TTreeNode const * const pRoot) {
if (pRoot != 0) {
std::cout << pRoot->Data << std::endl;
// take care of left node
if(pRoot->pLeft || pRoot->pRight) std::cout << ",";
PrintPreOrder(pRoot->pLeft);
// take care of right node
if(pRoot->pLeft && pRoot->pRight) std::cout << ",";
PrintPreOrder(pRoot->pRight);
}
}
答案 2 :(得分:0)
所以看起来应该是这样的:
void PrintPreOrder(TTreeNode const * const pRoot) {
if (pRoot) {
// print the root:
std::cout << pRoot->Data;
// visit the left subtree:
if (pRoot->pLeft) {
std::cout << ",";
PrintPreOrder(pRoot->pLeft);
}
// visit the right subtree:
if (pRoot->pRight) {
std::cout << ",";
PrintPreOrder(pRoot->pRight);
}
}
}
答案 3 :(得分:0)
我知道这已经有好几年了,但仍然很有帮助!
我想知道如何自己做这件事,发现了这个问题,但意识到有一个简单的答案:
void Preorder(Node* root){
if(root==NULL){
return;
}
cout << root->data << " ";
Preorder(root->left);
Preorder(root->right);
}
您从树的根开始。如果根是null
,则代码完成。
否则,打印出该节点的数据。
然后,我们在该节点的Preorder
和left
子树上调用right
,该子节点现在是其子树的root
。重要的是我们首先调用左子树,因为这是预订(对于后期订单的右子树)。
我们检查root
是否为null
,因此我们不必担心左子树是null
还是right
子树是{{ 1}}单独。如果节点是null
,则只需回溯。