-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstruct_binary_tree_from_postorder.cpp
More file actions
82 lines (72 loc) · 2.1 KB
/
construct_binary_tree_from_postorder.cpp
File metadata and controls
82 lines (72 loc) · 2.1 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// =====================================================================================
//
// Filename: construct_binary_tree_from_postorder.cpp
//
// Description: 106. Construct Binary Tree from Inorder and Postorder Traversal.
//
// Version: 1.0
// Created: 08/09/2019 05:43:23 PM
// Revision: none
// Compiler: g++
//
// Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
// Organization:
//
// =====================================================================================
#include <stdio.h>
#include <vector>
using std::vector;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution
{
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder)
{
if (inorder.size() != postorder.size())
{
return nullptr;
}
return buildTree(inorder, postorder, 0, 0, postorder.size());
}
private:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder,
int in_idx, int post_idx, int size)
{
if (size <= 0)
{
return nullptr;
}
int i = 0;
for (i = in_idx; i < (in_idx + size); i++)
{
if (inorder[i] == postorder[post_idx + size - 1])
{
break;
}
}
if (i >= (in_idx + size))
{
return nullptr;
}
auto* root = new TreeNode(postorder[post_idx + size - 1]);
int left_size = i - in_idx;
int right_size = size - left_size - 1;
root->left = buildTree(inorder, postorder, in_idx, post_idx, left_size);
root->right = buildTree(inorder, postorder, i + 1, post_idx + left_size, right_size);
return root;
}
};
int main(int argc, char* argv[])
{
vector<int> inorder = {9, 3, 15, 20, 7};
vector<int> postorder = {9, 15, 7, 20, 3};
auto* root = Solution().buildTree(inorder, postorder);
printf("root != nullptr -> %s\n", ((root != nullptr) ? "true" : "false"));
return 0;
}