根据前序遍历和中序遍历重建二叉树
[左子树,根, 右子树]
,递归建立二叉树就好class Solution {
public:
TreeNode* build(vector<int>& preorder, int preL, int preR, vector<int>& inorder, int inL, int inR) {
if(preL > preR) {
return NULL;
}
int pos = 0;
int root_val = preorder[preL];
TreeNode* root = new TreeNode(root_val);
for(pos=inL;pos<inR;pos++) {
if(inorder[pos] == root_val) {
break;
}
}
int numLeft = pos - inL;
root->left = build(preorder, preL + 1, preL + numLeft, inorder, inL, pos - 1);
root->right = build(preorder, preL + numLeft + 1, preR, inorder, pos + 1, inR);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
TreeNode* root = build(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
return root;
}
};
原文:https://www.cnblogs.com/MartinLwx/p/14273804.html