面试题07. 根据前序和中序重建二叉树

Posted ocpc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面试题07. 根据前序和中序重建二叉树相关的知识,希望对你有一定的参考价值。

题目:

技术图片

 

 

解答:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* buildTreeHelper(vector<int> &preorder, int ps, int pe, vector<int> &inorder, int is, int ie)
13     {
14         if ((pe - ps) < 0 || ((pe - ps) != (ie - is)))
15         {
16             return NULL;
17         }
18 
19         TreeNode *root = new TreeNode(preorder[ps]);
20 
21         int index = -1;
22         for (int i = is; i <= ie; i++)
23         {
24             if (inorder[i] == root->val)
25             {
26                 index = i;
27                 break;
28             }
29         }
30 
31         if (-1 == index)
32         {
33             return root;
34         }
35 
36         int leftprelen = index - is;
37         root->left = buildTreeHelper(preorder, ps + 1, ps + leftprelen, inorder, is, index - 1);
38         root->right = buildTreeHelper(preorder, ps + leftprelen + 1, pe, inorder, index + 1, ie);
39         return root;
40     }
41     TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) 
42     {
43         return buildTreeHelper(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() -1);
44     }
45 };

 

以上是关于面试题07. 根据前序和中序重建二叉树的主要内容,如果未能解决你的问题,请参考以下文章

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

用前序和中序重建二叉树 python

剑指Offer——面试题7:重建二叉树

由先序和中序重建二叉树

面试题07:重建二叉树(C++)

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