题解 | #重建二叉树#
重建二叉树
https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <algorithm> #include <iterator> #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param preOrder int整型vector * @param vinOrder int整型vector * @return TreeNode类 */ TreeNode* reConstructBinaryTree(vector<int>& preOrder, vector<int>& vinOrder) { // write code here if (preOrder.size()==0||vinOrder.size()==0) { return nullptr; } TreeNode * tree=new TreeNode(preOrder[0]); int mid=distance(begin(vinOrder), find(vinOrder.begin(), vinOrder.end(), preOrder[0])); vector<int> preleft(preOrder.begin() + 1,preOrder.begin() + 1+ mid); vector<int> preright(preOrder.begin()+mid+1,preOrder.end()); vector<int> left_in(vinOrder.begin(), vinOrder.begin() + mid); vector<int> right_in(vinOrder.begin() + mid + 1, vinOrder.end()); tree->left=reConstructBinaryTree(preleft, left_in); tree->right=reConstructBinaryTree(preright, right_in); return tree; } };