欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

剑指offer. 面试题07. 重建二叉树

程序员文章站 2022-06-17 17:09:12
...

输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

剑指offer. 面试题07. 重建二叉树 

思路经典啊! 

 TreeNode* recursion(vector<int>& preorder, int i1, int j1, vector<int>& inorder, int i2, int j2) {

         if (i1 > j1 || i2 > j2)
                 return nullptr;

         TreeNode* head = new TreeNode(preorder[i1]);

         int loc = i2;
         for (; loc <= j2; loc++)
                 if (head->val == inorder[loc])
                         break;

         int diff = loc - i2;

         head->left = recursion(preorder, i1 + 1, i1 + diff, inorder, i2, loc - 1);
         head->right = recursion(preorder, i1 + diff + 1, j1, inorder, loc + 1, j2);

         return head;
 }

 TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {

         TreeNode* head = recursion(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
         return head;
 }