LeetCode 105.从前序与中序遍历序列构造二叉树
题目链接:https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
题目
解答
同LeetCode 106的思路一致
class Solution {
private:
TreeNode* traversal(vector<int>& preorder, vector<int>& inorder){
if(preorder.size() == 0) return NULL;
//前序遍历数组的第一个元素就是当前的中间节点
int rootValue = preorder[0];
TreeNode* root = new TreeNode(rootValue);
//叶子节点
if(preorder.size() == 1) return root;
//找到中序遍历的切割点
int delimiterIndex;
for(delimiterIndex = 0; delimiterIndex < inorder.size(); delimiterIndex++){
if(inorder[delimiterIndex] == rootValue){
break;
}
}
//切割中序数组
vector<int> leftInorder(inorder.begin(), inorder.begin() + delimiterIndex);
vector<int> rightInorder(inorder.begin() + delimiterIndex + 1, inorder.end());
//舍弃首位元素
preorder.erase(preorder.begin());
//切割前序数组
vector<int> leftPreorder(preorder.begin() , preorder.begin() + leftInorder.size());
vector<int> rightPreorder(preorder.begin() + leftInorder.size(), preorder.end());
root->left = traversal(leftPreorder, leftInorder);
root->right = traversal(rightPreorder, rightInorder);
return root;
}
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(inorder.size() == 0 || preorder.size() == 0) return NULL;
return traversal(preorder, inorder);
}
};