首页 > 其他 > 详细

【树】106. 从中序与后序遍历序列构造二叉树

时间:2020-05-02 13:53:19      阅读:54      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

 

 

 

解答:

 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 };

 

【树】106. 从中序与后序遍历序列构造二叉树

原文:https://www.cnblogs.com/ocpc/p/12817685.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!