首页 > 代码库 > [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
class Solution {public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { int len = inorder.size(); return build(inorder,0,len-1,postorder,0,len-1); }private: TreeNode * build(vector<int> &inorder,int begInorder,int endInorder, vector<int> &postorder,int begpostorder,int endpostorder){ if(begInorder>endInorder || begpostorder>endpostorder) return NULL; int val = postorder[endpostorder]; TreeNode *root = new TreeNode(val); if(endInorder==begInorder) return root; int i,j=0; for(i=begInorder;i<=endInorder;i++,j++){ if(inorder[i]==val) break; } root->left = build(inorder,begInorder,i-1,postorder,begpostorder,begpostorder+j-1); root->right = build(inorder,i+1,endInorder,postorder,begpostorder+j,endpostorder-1); return root; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。