给定两个整数数组 preorder
和 inorder
,其中 preorder
是二叉树的先序遍历, inorder
是同一棵树的中序遍历,请构造二叉树并返回其根节点。
示例 1:
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] 输出: [3,9,20,null,null,15,7]
提示:
1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder
和inorder
均 无重复 元素inorder
均出现在preorder
preorder
保证 为二叉树的前序遍历序列inorder
保证 为二叉树的中序遍历序列
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
TreeNode* Pre_In_Creater(vector<int>& preorder, int preleft, int preright, vector<int>& inorder, int inleft, int inright) {
if (preleft > preright || inleft > inright) return nullptr; // 检查边界条件
int hnode = preorder[preleft]; // 前序遍历的第一个元素是根节点
TreeNode* node = new TreeNode(hnode); // 创建根节点并初始化
int index = inleft;
while (inorder[index] != hnode) {
index++;
}
// 递归构建左子树和右子树
node->left = Pre_In_Creater(preorder, preleft + 1, preleft + index - inleft, inorder, inleft, index - 1);
node->right = Pre_In_Creater(preorder, preleft + index - inleft + 1, preright, inorder, index + 1, inright);
return node;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if (preorder.empty() || inorder.empty() || preorder.size() != inorder.size()) return nullptr;
return Pre_In_Creater(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
}
};