首页 > 代码库 > 先序+中序和中序+后序建树
先序+中序和中序+后序建树
思路:先序的第一个元素和后序的最后一个元素是当前子树的根,然后遍历中序序列,找到左右子树的分界线,递归建左子树和右子树。
class Solution { public: /*由于是oj,这里假设给的序列是合法的,正常情况是需要判断不合法情况的 */ TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder,int instart,int inend,int poststart,int postend) { TreeNode* root = new TreeNode(postorder[postend]); if(instart == inend && poststart == postend && instart == poststart)return root; int i; for(i = instart;i <= inend;++i) { if(inorder[i] == postorder[postend])break;//找到中序的根节点 } if(i > instart)root -> left = buildTree(inorder,postorder,instart,i - 1,poststart,poststart + (i - instart - 1)); if(i < inend) root -> right = buildTree(inorder,postorder,i + 1,inend,poststart + i - instart,postend - 1); return root; } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { int inlength = inorder.size(),postlength = postorder.size(); if( inlength == 0 || inlength != postlength ) return NULL; return buildTree(inorder,postorder,0,inlength-1,0,postlength-1); } }; class Solution { public: TreeNode *buildTree(vector<int>& preorder,vector<int> &inorder,int prestart,int preend,int instart,int inend) { TreeNode* root = new TreeNode(preorder[prestart]); if(instart == inend && prestart == preend && instart == prestart)return root; int i; for(i = instart;i <= inend;++i) { if(inorder[i] == preorder[prestart])break;//找到中序的根节点 } if(i > instart)root -> left = buildTree(preorder,inorder,prestart+1,prestart + i - instart,instart,i - 1); if(i < inend) root -> right = buildTree(preorder,inorder,prestart + i - instart + 1,preend,i + 1,inend); return root; } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { int prelength = preorder.size(),inlength = inorder.size(); if( inlength == 0 || inlength != prelength ) return NULL; return buildTree(preorder,inorder,0,prelength-1,0,inlength-1); } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。