根据前序遍历和中序遍历树构造二叉树.
给出中序遍历:[1,2,3]
和前序遍历:[2,1,3]
. 返回如下的树:
2
/ \
1 3
解题思路:1.先序遍历的第一个节点为根节点。2.在中序遍历中定位到根节点的位置,左半部分即为左子树,右半部分即为右子树。3.利用递归思想重构二叉树。
已AC的两种代码:/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { /** *@param preorder : A list of integers that preorder traversal of a tree *@param inorder : A list of integers that inorder traversal of a tree *@return : Root of a tree */ public: TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { if(preorder.size()==0||inorder.size()==0) { return NULL; } TreeNode*sroot=new TreeNode(preorder[0]); sroot->left=NULL; sroot->right=NULL; int pos=-1; vector<int>preleft; vector<int>preright; vector<int>inleft; vector<int>inright; int sl=0; int sr=0; for(int i=0;i<inorder.size();i++) { if(inorder[i]==preorder[0]) { pos=i; break; } } for(int i=0;i<inorder.size();i++) { if(i<pos) { inleft.push_back(inorder[i]); sl++; } if(i>pos) { inright.push_back(inorder[i]); sr++; } } for(int i=1;i<preorder.size();i++) { if(sl) { preleft.push_back(preorder[i]); --sl; continue; } if(sr) { preright.push_back(preorder[i]); --sr; } } sroot->left=buildTree(preleft,inleft); sroot->right=buildTree(preright,inright); return sroot; // write your code here } };
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { /** *@param preorder : A list of integers that preorder traversal of a tree *@param inorder : A list of integers that inorder traversal of a tree *@return : Root of a tree */ public: TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { if(preorder.size()==0||inorder.size()==0) { return NULL; } TreeNode*sroot=new TreeNode(preorder[0]); sroot->left=NULL; sroot->right=NULL; vector<int>preleft; vector<int>preright; vector<int>inleft; vector<int>inright; int pos=find(inorder.begin(),inorder.end(),preorder[0])-inorder.begin(); inleft.assign(inorder.begin(),inorder.begin()+pos); inright.assign(inorder.begin()+pos+1,inorder.end()); preleft.assign(preorder.begin()+1,preorder.begin()+pos+1); preright.assign(preorder.begin()+pos+1,preorder.end()); sroot->left=buildTree(preleft,inleft); sroot->right=buildTree(preright,inright); return sroot; // write your code here } };