我正在从给定的中序和先序遍历数组创建一个二叉树,我不知道为什么它会给我错误的输出,尽管它对给定数组中的某些点非常有效
#include<iostream>
using namespace std;
class Node
{
public:
int i;
Node* left;
Node* right;
bool isThreaded;
Node(int j);
};
Node::Node(int j):i(j)
{
left=NULL;
right=NULL;
}
void inorder(Node* root)
{
if(root)
{
inorder(root->left);
cout<<root->i<<" ";
inorder(root->right);
}
}
int findkey(int* a, int l, int r, int key)
{
for(int i=l; i<r; i++)
{
if(a[i]==key)
return i;
}
return -1;
}
Node* ConstructfromPreorderInorder(int* pre, int n, int* in, int l, int r, int& k)
{
Node* root=NULL;
if(k<n && l<r)
{
int key=findkey(in, l, r, pre[k]); //Finds the index of current preorder element in inorder array
root=new Node(pre[k++]); //Forms the node
root->left=ConstructfromPreorderInorder(pre, n, in, 0, key, k); //To find the left subtree we traverse to left of the index of element in inroder array
root->right=ConstructfromPreorderInorder(pre, n, in, key+1, r, k);
//Similarly we traverse right to form right subtree
}
return root;
}
int main()
{
int pre[]={1,2,4,5,3,6,7};
int in[]={4,2,5,1,6,3,7};
int n=sizeof(pre)/sizeof(*pre); //Function used to find the no. of elements in an array. In this case elements in preorder array. Both are same so can use any
int i=0;
Node* root2=ConstructfromPreorderInorder(pre, n, in, 0, n, i);
inorder(root2);
}
虽然它适用于数组中的一半元素,但在那之后它会给出不寻常的结果。为了更好地查看,我添加了打印语句。
如果对您有帮助,请采纳。
最佳答案
构造左子树范围应该从 l 而不是 0 开始。
root->left=ConstructfromPreorderInorder(pre, n, in, l, key, k);
代替
root->left=ConstructfromPreorderInorder(pre, n, in, 0, key, k);
关于c++ - 从给定的中序和前序遍历构造二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30243371/