-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path106.cpp
More file actions
46 lines (42 loc) · 1.11 KB
/
106.cpp
File metadata and controls
46 lines (42 loc) · 1.11 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
//
// 106.cpp
// LeetCode
//
// Created by 张佐玮 on 15/7/12.
// Copyright (c) 2015年 JarvisZhang. All rights reserved.
//
// Title: Construct Binary Tree from Inorder and Postorder Traversal
//
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
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) {
stack<TreeNode*> parents;
int i = 0, j = 0;
TreeNode *current = nullptr;
while (j < postorder.size()) {
if (!parents.empty() && parents.top() -> val == postorder[j]) {
parents.top() -> right = current;
current = parents.top();
parents.pop();
j++;
}
else {
TreeNode *newNode = new TreeNode(inorder[i++]);
newNode -> left = current;
parents.push(newNode);
current = nullptr;
}
}
return current;
}
};