105. 从前序与中序遍历序列构造二叉树 ------ 递归
给定两个整数数组 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 保证 为二叉树的中序遍历序列
通过次数438,386提交次数614,276
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/** * 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) {} * }; */ //preorder第一个元素为root,在inorder里面找到root,在它之前的为左子树(长l1),之后为右子树(长l2)。preorder[1]到preorder[l1]为左子树,之后为右子树,分别递归。 class Solution { public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { return pre_order(0, inorder.size() - 1, 0, inorder.size() - 1, preorder, inorder); } TreeNode *pre_order(int leftpre, int rightpre, int leftin, int rightin, vector<int> &pre, vector<int> &in) { if (leftpre > rightpre || leftin > rightin) return NULL; TreeNode *root = new TreeNode(pre[leftpre]); int rootin = leftin; while (rootin <= rightin && in[rootin] != pre[leftpre]) rootin++; int left = rootin - leftin; root->left = pre_order(leftpre + 1, leftpre + left, leftin, rootin - 1, pre, in); root->right = pre_order(leftpre + left + 1, rightpre, rootin + 1, rightin, pre, in); return root; } };
hello my world
本文来自博客园,作者:slowlydance2me,转载请注明原文链接:https://www.cnblogs.com/slowlydance2me/p/16900253.html