目录
一:题目:
给定两个整数数组 preorder
和 inorder
,其中 preorder
是二叉树的先序遍历 , inorder
是同一棵树的中序遍历,请构造二叉树并返回其根节点。
二:代码:
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
TreeNode* travsal(vector<int>& pre, vector<int>& in){
if(pre.size()==0) return NULL;
int target=pre[0];
TreeNode* root=new TreeNode(target);
if(pre.size()==1) return root;
int i;
for(i=0;i<in.size();i++){
if(in[i]==target) break;
}
vector<int> leftin(in.begin(),in.begin()+i);
vector<int> rightin(in.begin()+1+i,in.end());
pre.erase(pre.begin()+0);
vector<int> leftpre(pre.begin(),pre.begin()+leftin.size());
vector<int> rightpre(pre.begin()+leftin.size(),pre.end());
root->left=travsal(leftpre,leftin);
root->right=travsal(rightpre,rightin);
return root;
}
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.size()==0||inorder.size()==0) return NULL;
return travsal(preorder,inorder);
}
};