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