c++ - Constructing Binary tree from given inorder and preorder traversals -
i making binary tree given inorder , preorder traversal array , don't know why giving me wrong output although works points in given array
#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 index of current preorder element in inorder array root=new node(pre[k++]); //forms node root->left=constructfrompreorderinorder(pre, n, in, 0, key, k); //to find left subtree traverse left of index of element in inroder array root->right=constructfrompreorderinorder(pre, n, in, key+1, r, k); //similarly traverse right 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 find no. of elements in array. in case elements in preorder array. both same can use int i=0; node* root2=constructfrompreorderinorder(pre, n, in, 0, n, i); inorder(root2); }
although works the half of elements in array after gives unusual results. have added print statements better view.
please see if helps.
for constructing left subtree range should start l instead of 0.
root->left=constructfrompreorderinorder(pre, n, in, l, key, k);
instead of
root->left=constructfrompreorderinorder(pre, n, in, 0, key, k);
Comments
Post a Comment