面试题07-I. 根据中序和后序重建二叉树

Posted ocpc

tags:

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

题目:

技术图片

 

 

解答:

 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 *buildTree(vector<int> &iorder, int isi, int iei, vector<int> &porder, int psi, int pei)
13     {
14         if(iei - isi < 0 || iei - isi != pei - psi)
15         {
16             return NULL;
17         }
18 
19         //the porder[pei] is the root of this tree
20 
21         TreeNode *root = new TreeNode(porder[pei]);
22         
23         //find the root in the iorder to seperate it into left sub tree and right sub tree
24         //root index in inorder array
25 
26         int riii = -1;    
27         for(int i = isi; i <= iei; ++i)
28         {
29             if(iorder[i] == root->val)
30             {
31                 riii = i;
32                 break;
33             }
34         }
35         if(riii == -1)
36         {
37             return root;//error
38         }
39 
40         int lnodes = riii - isi;
41 
42         //for the left sub tree
43         //the isi to riii - 1 in inorder array will be it‘s inorder traversal
44         //and the psi to psi + lnodes - 1 in postorder array will be it‘s post order traversal
45 
46         root->left = buildTree(iorder, isi, riii - 1, porder, psi, psi + lnodes - 1);
47         
48         //for the right sub tree is similary to the left
49 
50         root->right = buildTree(iorder, riii + 1, iei, porder, psi + lnodes, pei - 1);
51 
52         return root;
53     }
54     TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
55     {
56         return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() -1);
57     }
58 };

 

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

重建二叉树

重建二叉树

5.根据前序和中序得到二叉树代码实现,根据中序和后序得到二叉树代码实现(JavaScript版)

怎么根据二叉树的前序,中序,确定它的后序

面试题07-II 根据前序和后序遍历构造二叉树

面试题07-II 根据前序和后序遍历构造二叉树