题目描述:
从中序遍历和先序遍历重建二叉树
思路:
递归
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode * dfs(TreeNode *root,int root_pos,int inl,int inr,vector<int>& preorder,vector<int>& inorder){
if(inl>inr)return root;
if(root==nullptr){
root = new TreeNode(preorder[root_pos]);
}
int i= inl;
while(preorder[root_pos]!=inorder[i])i++; //寻找头结点在中序遍历中的位置
root->left=dfs(root->left,root_pos+1,inl,i-1,preorder,inorder);
root->right= dfs(root->right,root_pos+i-inl+1,i+1,inr,preorder,inorder);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
TreeNode *root = nullptr;
root=dfs(root,0,0,inorder.size()-1,preorder,inorder);
return root;
}
};