树遍历未打印正确的顺序
Tree Traversal not printing correct order
我在C++的类中创建了一个二叉树。我的插入函数是非递归的,看起来像这样:
bool Tree1::inOrderInsert(int x)
{
TreeNode *parent = NULL;
TreeNode *temp = root;
TreeNode *newNode = new TreeNode(x);
if (root == NULL)
{
root = newNode;
//cout << "Root empty!" << endl;
return true;
}
while (temp != NULL)
{
if (x <= temp->value)
{
parent = temp;
temp = temp->left;
}
else
{
parent = temp;
temp = temp->right;
}
}
if (x <= parent->value)
{
parent->left = newNode;
return true;
}
else
{
parent->right = newNode;
return true;
}
}
我使用此功能使用后序遍历和打印树:
void Tree1::postOrderPrintRec(TreeNode *node)
{
if (node != NULL)
{
preOrderPrintRec(node->left);
preOrderPrintRec(node->right);
cout << "Value: " << node->value << endl;
}
}
我在 main 中插入和打印值,如下所示:
tree1.inOrderInsert(5);
tree1.inOrderInsert(3);
tree1.inOrderInsert(2);
tree1.inOrderInsert(4);
tree1.inOrderInsert(6);
tree1.inOrderInsert(7);
tree1.postOrderPrintRec(tree1.getRoot());
运行代码时我应该看到的值如下:值:2值:4值:3值:7值:6值:5
但是,我看到的是:值:3值:2值:4值:6值:7值:5
谁能告诉我为什么它以不正确的顺序打印出值?
你在postOrderPrintRec()
函数中调用preOrderPrintRec()
。 这意味着您只在树的顶层执行后序遍历。 改为打电话给postOrderPrintRec()
,我认为这将解决它。
相关文章:
- 如何在C++中递归地按相反顺序打印集合
- 首先按给定顺序打印所有数字,然后使用 Array 打印所有字符和其他符号
- 按字母顺序打印存储在字符数组中的信息
- 视觉C++未按所需顺序打印
- C++使用相反的顺序打印带有逗号的列表
- C/C++ - 用于按顺序打印数字的 sem_t 类型的单个信号量
- 如何以相反顺序C 打印整数的单个数字
- 我不知道如何创建一个以数字/字母顺序打印出我的整数或字符串的程序
- 在 C Linux 中使用三个线程使用信号量同步按顺序打印 3 4 5 50 次
- 以相反的顺序打印链表的后半部分
- 我如何附加双链接以指向正确的节点,以相反的顺序打印
- 按字母顺序打印结构输入C
- 按顺序打印时遇到问题,二叉树的后顺序等
- 按特定顺序打印队列
- 输出未按正确的顺序打印
- 按字典顺序打印给定字符串的所有字母组合的算法
- 使用基于范围的 for 循环以相反的顺序打印矢量
- C++链表-按排序顺序打印
- 我如何使用C ++以相反的顺序打印此单个链表中的元素
- 如何使链接列表按字母顺序打印其内容