机试练习7.11

xiaoxiao2021-02-28  71

题目描述 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。 前序遍历是:根左右 中序遍历是:左根右 后续遍历是:左右根 这里使用递归,对前序遍历和中序遍历使用指针的递归即可。

/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { TreeNode * root=reConstructBinaryTree(pre,0,pre.size()-1,vin,0,vin.size()-1); return root; } private: TreeNode * reConstructBinaryTree(vector<int> pre,int prep,int pred,vector<int>vin,int vinp,int vind) { if(prep>pred||vinp>vind) return NULL; TreeNode *root=new TreeNode(pre[prep]); for(int i=vinp;i<=vind;i++)//注意这里的i不是从0开始的!! { if(pre[prep]==vin[i]) { root->left=reConstructBinaryTree(pre,prep+1,prep+i-vinp,vin,vinp,i-1); root->right=reConstructBinaryTree(pre,prep+i+1-vinp,pred,vin,i+1,vind); } } return root; } };
转载请注明原文地址: https://www.6miu.com/read-79973.html

最新回复(0)