根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3 / \ 9 20 / \ 15 7
第一眼看到这题我就懵逼了,wtf???
但是仔细想一下虽然复杂,但是很简单。。。前序数组的结构为【根,左子树,右子树】,中序数组结构为【左子树,根,右子树】,那么先从前序数组确定根,然后用根把中序数组分成【左子树】和【右子树】,再在前序数组里根据左子树的长度确定右子树的根位置,左子树的根位置就是父节点位置+1,然后把左右子树当成新树递归就好了。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ struct TreeNode *build(int* preorder,int prel,int* inorder,int inl,int inr) { if(inl>=inr) return NULL; struct TreeNode *root=(struct TreeNode *)malloc(sizeof(struct TreeNode)); root->val=preorder[prel]; int i; for(i=inl;i<inr;i++) if(inorder[i]==preorder[prel]) break; root->left=build(preorder,prel+1,inorder,inl,i); root->right=build(preorder,prel+1+(i-inl),inorder,i+1,inr); return root; } struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) { struct TreeNode *root=build(preorder,0,inorder,0,inorderSize); return root; }
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3 / \ 9 20 / \ 15 7