剑指Offer——重建二叉树
Question
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
Solution
首先先序遍历的第一个数字是根,然后从中序遍历中,通过根的值,可以将数组分为左子树(左边的)和右子树(右边的)。
然后取出左子树的先序遍历和中序遍历部分就可以用于构建这颗子树,方法和刚才一样,可以看到这个是一个递归的过
程,右子树同理。
Code
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
if (pre.size() == 0 || vin.size() == 0)
return NULL;
return ConstructBinaryTreeCore(pre, vin, 0, pre.size() - 1, 0, vin.size() - 1);
}
TreeNode* ConstructBinaryTreeCore(vector<int>& pre, vector<int>& vin,
int pre_start, int pre_end, int vin_start, int vin_end) {
int rootValue = pre[pre_start];
TreeNode* root = new TreeNode(rootValue);
if (pre_start == pre_end) {
if (vin_start == vin_end)
return root;
else {
//throw exception("Invalid input");
}
}
int rootVin = vin_start;
while (rootVin <= vin_end && vin[rootVin] != rootValue)
rootVin++;
if (vin_start == vin_end && vin[rootVin] != rootValue) {
//throw exception("Invalid input");
}
int leftLength = rootVin - vin_start;
int leftPreEnd = pre_start + leftLength;
if (leftLength > 0) {
root->left = ConstructBinaryTreeCore(pre, vin, pre_start + 1, leftPreEnd, vin_start, rootVin - 1);
}
if (leftLength < pre_end - pre_start) {
root->right = ConstructBinaryTreeCore(pre, vin, leftPreEnd + 1, pre_end, rootVin + 1, vin_end);
}
return root;
}
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步