剑指offer. 面试题07. 重建二叉树
程序员文章站
2022-06-17 17:09:12
...
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
思路经典啊!
TreeNode* recursion(vector<int>& preorder, int i1, int j1, vector<int>& inorder, int i2, int j2) {
if (i1 > j1 || i2 > j2)
return nullptr;
TreeNode* head = new TreeNode(preorder[i1]);
int loc = i2;
for (; loc <= j2; loc++)
if (head->val == inorder[loc])
break;
int diff = loc - i2;
head->left = recursion(preorder, i1 + 1, i1 + diff, inorder, i2, loc - 1);
head->right = recursion(preorder, i1 + diff + 1, j1, inorder, loc + 1, j2);
return head;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
TreeNode* head = recursion(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
return head;
}
上一篇: 设计模式与应用:状态模式
下一篇: 剑指offer——数值的整数次方
推荐阅读