其他分享
首页 > 其他分享> > 面试题07-I. 根据中序和后序重建二叉树

面试题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 };

 

标签:面试题,psi,TreeNode,07,int,riii,isi,二叉树,root
来源: https://www.cnblogs.com/ocpc/p/12856591.html