题解 | #牛群的树形结构重建II#
牛群的树形结构重建II
https://www.nowcoder.com/practice/ad81ec30cca0477e82e33334a652a6ae
题目考察的知识点:二叉树结构重建
题目解答方法的文字分析:以先序确定根节点,在中序中找到根节点的位置,就可以确认左子树和右子树,分别遍历左子树、右子树。
本题解析所用的编程语言:c++
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param preOrder int整型vector * @param inOrder int整型vector * @return TreeNode类 */ TreeNode* _buildTreeII(vector<int>& preOrder, vector<int>& inOrder, int& prei, int inbegin, int inend) { if (inbegin > inend) return nullptr; TreeNode* root = new TreeNode(preOrder[prei]); int rooti = inbegin; while (rooti <= inend) { if (inOrder[rooti] == preOrder[prei]) break; ++rooti; } ++prei; root->left = _buildTreeII(preOrder, inOrder, prei, inbegin, rooti - 1); root->right = _buildTreeII(preOrder, inOrder, prei, rooti + 1, inend); return root; } TreeNode* buildTreeII(vector<int>& preOrder, vector<int>& inOrder) { // write code here int i = 0; return _buildTreeII(preOrder, inOrder, i, 0, inOrder.size() - 1); } };