码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-05-09 13:03:22      阅读:62      评论:0      收藏:0      [点我收藏+]

标签:turn   pre   err   node   sub   color   bin   ini   his   

题目:

技术图片

 

 

解答:

 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. 根据中序和后序重建二叉树

标签:turn   pre   err   node   sub   color   bin   ini   his   

原文地址:https://www.cnblogs.com/ocpc/p/12856591.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!