给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。
示例 1:
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
输出: [3,9,20,null,null,15,7]
示例 2:
输入: preorder = [-1], inorder = [-1]
输出: [-1]
提示:
1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder 和 inorder 均 无重复 元素
inorder 均出现在 preorder
preorder 保证 为二叉树的前序遍历序列
inorder 保证 为二叉树的中序遍历序列
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal
思路:东哥带你刷二叉树(构造篇) :: labuladong的算法小抄
c++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector& preorder, vector& inorder) {
return buildTree(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}
TreeNode* buildTree(vector& preorder, int preStart, int preEnd, vector& inorder, int inStart, int inEnd) {
if(preStart>preEnd || inStart>inEnd) {
return nullptr;
}
int inIndex = inStart;
for(int i=inStart;i<=inEnd;i++) {
if(preorder[preStart] == inorder[i]) {
inIndex = i;
break;
}
}
// 以 preorder[preStart] 为根节点的左子树节点的个数
int leftSize = inIndex - inStart;
// 以 preorder[preStart] 为根节点的右子树节点的个数
int rightSize = inEnd - inIndex;
TreeNode* root = new TreeNode(preorder[preStart]);
root->left = buildTree(preorder,preStart + 1, preStart + leftSize, inorder, inIndex - leftSize, inIndex-1);
root->right = buildTree(preorder,preStart+leftSize +1, preEnd,inorder,inIndex+1,inIndex + rightSize);
return root;
}
};