题解 | #重建二叉树#
重建二叉树
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 <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.empty() || vinOrder.empty()){ return nullptr; } auto node = new TreeNode(preOrder[0]); if(preOrder.size() == 1){ return node; } auto it = find(vinOrder.begin(), vinOrder.end(),preOrder[0]); if(it != vinOrder.end()){ vector<int> left_inorder(vinOrder.begin(), it); vector<int> right_inorder(it + 1, vinOrder.end()); int nleft = left_inorder.size(); int nright = right_inorder.size(); vector<int> left_preorder(preOrder.begin()+1,preOrder.begin()+nleft+1); vector<int> right_preorder(preOrder.begin() + nleft + 1, preOrder.end()); node ->left = reConstructBinaryTree(left_preorder, left_inorder); node ->right = reConstructBinaryTree(right_preorder, right_inorder); } return node; } };