刷题-力扣-105. 从前序与中序遍历序列构造二叉树
105. 从前序与中序遍历序列构造二叉树
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
题目分析
- 根据先序和中序遍历序列构造二叉树
- 先找到父节点,再遍历其子节点
- 在先序序列中找到父节点,根据父节点在中序序列中找出左右子树的结点序列
代码
/**
* 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) {
int preorderLen = preorder.size();
int inorderLen = inorder.size();
if (preorderLen == 0 || inorderLen == 0) return nullptr;
return recursion(preorder, 0, preorderLen - 1, inorder, 0, inorderLen - 1);
}
private:
TreeNode* recursion(vector<int>& preorder, int preorderLeft, int preorderRight, vector<int>& inorder, int inorderLeft, int inorderRight) {
if (preorderLeft > preorderRight || inorderLeft > inorderRight) return nullptr;
TreeNode* node = new TreeNode(preorder[preorderLeft]);
int mid;
for (mid = inorderLeft; mid <= inorderRight; ++mid) {
if (inorder[mid] == preorder[preorderLeft]) break;
}
node->left = recursion(preorder, preorderLeft + 1, preorderLeft + mid - inorderLeft, inorder, inorderLeft, mid - 1);
node->right = recursion(preorder, preorderLeft + mid - inorderLeft + 1, preorderRight, inorder, mid + 1, inorderRight);
return node;
}
};