本文主要是介绍leetcode 106:从中序与后序遍历序列构造二叉树,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本题与leetcode 105类似,只不过是前序遍历的第一个元素为root 而后序遍历的最后一个元素为root
https://mp.csdn.net/postedit/86372320
int find(int a,std::vector<int> b,int s,int t,int &c){c=0;for(int i=s;i<=t;i++){c++;if(a==b[i]){return i;}}
}TreeNode *build(std::vector<int>& postorder, std::vector<int>& inorder,int s1,int t1,int s2,int t2){if(s1<t1&&s2<t2){TreeNode *root=new TreeNode(postorder[t1]);int c=0;int f=find(postorder[t1],inorder,s2,t2,c);root->left=build(postorder,inorder,s1,s1+c-2,s2,f-1);root->right=build(postorder,inorder,s1+c-1,t1-1,f+1,t2);return root;}else if(s1==t1){TreeNode *root=new TreeNode(postorder[s1]);return root;}elsereturn NULL;}TreeNode* buildTree(std::vector<int>& inorder, std::vector<int>& postorder) {TreeNode *root=build(postorder,inorder,0,postorder.size()-1,0,inorder.size()-1);return root;
}
这篇关于leetcode 106:从中序与后序遍历序列构造二叉树的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!