文章目录
1.题目
-
题目要求
-
思路:题目要求用先序和中序遍历来建立二叉树。
-
eg:
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
- eg:下面来看一个例子, 某一二叉树的中序和后序遍历分别为:
2.代码
class Solution
{
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
{
return SubbuildTree(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}
TreeNode* SubbuildTree(vector<int>& preorder, int pleft, int pright,vector<int>& inorder, int ileft, int iright)
{
if ((pleft > pright) || (ileft > iright)) return NULL;
int i=0;
for (i=ileft;i<iright;++i)
{
if (inorder[i] == preorder[pleft])
break;
}
TreeNode* root = new TreeNode(preorder[pleft]);
root ->left=SubbuildTree(preorder,pleft+1,pleft+i-ileft,inorder,ileft,i-1);
root ->right=SubbuildTree(preorder,pleft+i-ileft+1,right,inorder,i+1,iright);
}
};