106. Construct Binary Tree from Inorder and Postorder Traversal

每日一题 2019 - 04 - 24

题目:

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

1
2
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

解法:

这个题给出二叉树的中序遍历和后续遍历让还原出原先的二叉树,思路大概如下:

  • 后续遍历的最后一个结点为二叉树的根节点,找出根节点,在中序遍历中根据根节点将中序遍历分为左子树与右子树
  • 在中序遍历分开后的左子树右子树中继续进行划分,同时将后续遍历的序列也进行划分

递归这个过程即可完成还原;


代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return fun(inorder,postorder,0, inorder.size(), 0,postorder.size()-1);
}
TreeNode* fun(vector<int>& inorder, vector<int>& postorder,int in_start, int in_end, int post_start, int post_end)
{
if(post_start==post_end) return new TreeNode(postorder[post_end]);
if(post_start > post_end) return NULL;
int root_value=postorder[post_end];
TreeNode* root=new TreeNode(root_value);
int i=0;
for(;i<in_end;++i)
{
if(inorder[i]==root_value)
break;
}
root->left=fun(inorder,postorder,in_start, i-1, post_start, post_start+ i-in_start-1);
root->right=fun(inorder,postorder,i+1, in_end, post_start+i-in_start, post_end-1);
return root;
}
};
0%
undefined