首页 > 代码库 > leetcode-Construct Binary Tree from Preorder and Inorder Traversal
leetcode-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.
class Solution { private: TreeNode *root; vector<int> myPreOrder; vector<int> myInOrder; public: TreeNode *createTree(TreeNode *root,int pre,int in,int lenth) { int l,r,rootPos; if(lenth<=0) root=NULL; else { //新结点 root=new TreeNode(myPreOrder[pre]); //找根 for(int i=in;i<=in+lenth-1;i++) if(root->val==myInOrder[i]) rootPos=i; //子树长 l=rootPos-in; r=lenth-l-1; //建子树 root->left=createTree(root->left,pre+1,in,l); root->right=createTree(root->right, pre+1+l,rootPos+1,r); } return root; } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { if(preorder.size()<=0) return NULL; //复制 myPreOrder=preorder; myInOrder=inorder; //建树 root=createTree(root,0,0,preorder.size()); return root; } };
leetcode-Construct Binary Tree from Preorder and Inorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。