给定两个整数数组 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]
解题思路:
链接:https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solutions/107105/dong-hua-yan-shi-105-cong-qian-xu-yu-zhong-xu-bian/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
代码:
/**
* 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<int>& preorder, vector<int>& inorder) {
if (preorder.empty() || inorder.empty()) return nullptr;
TreeNode * subroot = new TreeNode(preorder[0]);
for(int i = 0; i < inorder.size() ; i++){
if(inorder[i]==preorder[0]){
vector<int> _pre(preorder.begin()+1,preorder.begin()+i+1);
vector<int> pre_(preorder.begin()+i+1,preorder.end());
vector<int> _in(inorder.begin(),inorder.begin()+i);
vector<int> in_(inorder.begin()+i+1,inorder.end());
subroot->left = buildTree(_pre,_in);
subroot->right = buildTree(pre_,in_);
break;
}
}
return subroot;
}
};