Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 关于树遍历_C++ - Fatal编程技术网

C++ 关于树遍历

C++ 关于树遍历,c++,C++,尝试了树遍历的代码,但没有得到预期的输出 tree* insertion(int data) { tree *ptr=new tree(); ptr->data=data; ptr->left=NULL; ptr->right=NULL; } void preorder(tree* root) { if(root==NULL) return; cout<<root->data<<" "; preorder(root->left

尝试了树遍历的代码,但没有得到预期的输出

tree* insertion(int data)
{
 tree *ptr=new tree();
 ptr->data=data;
 ptr->left=NULL;
 ptr->right=NULL;
}
void preorder(tree* root)
{
if(root==NULL)
    return;
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
void postorder(tree* root)
{
if(root==NULL)
    return;
preorder(root->left);
preorder(root->right);
cout<<root->data<<" ";
}
void inorder(tree* root)
{
if(root==NULL)
    return;
preorder(root->left);
cout<<root->data<<" ";
preorder(root->right);
}
预期输出:a顺序左、根、右:4 2 5 1 3 前序根,左,右:1 2 4 5 3 c后序左,右,根:4 5 2 3 1

我的输出:前序遍历:1 2 4 5 3 后序遍历:2 4 5 3 1
顺序遍历:2 4 5 1 3

在您调用的每个递归函数中,都是预顺序,而不是正确的函数。在inorder中,您应该调用inorder,在postorder中,您应该调用postorder


编辑:我看到函数插入的类型是tree*,但没有返回任何内容;可能您忘记了返回ptr

函数插入没有返回任何内容。注意:在使用复制/粘贴编程时,您应该更加小心。tree*插入数据-查找返回ptr;在那个函数中…找…找…找不到它。未定义的行为。感谢您的帮助。这是一个复制粘贴错误