Skip to content

Commit da5ccd8

Browse files
Add files via upload
1 parent fcbc1e2 commit da5ccd8

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// 和上一道题目的解题思路是一样的
2+
// 16ms 54.05%
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
14+
#include<vector>
15+
#include<algorithm>
16+
using namespace std;
17+
18+
class Solution {
19+
public:
20+
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder)
21+
{
22+
return helper(0, postorder.size() - 1, 0, inorder.size() - 1, postorder, inorder);
23+
}
24+
25+
TreeNode* helper(int postLeft, int postRight, int inLeft, int inRight, vector<int>& postorder, vector<int>& inorder)
26+
{
27+
if (postLeft > postRight)
28+
return 0;
29+
else if (postLeft == postRight)
30+
return new TreeNode(postorder[postLeft]);
31+
else
32+
{
33+
int rootValue = postorder[postRight];
34+
35+
vector<int>::iterator iter = find(inorder.begin() + inLeft, inorder.begin() + inRight + 1, rootValue);
36+
int rootIndex = iter - inorder.begin();
37+
38+
TreeNode *root = new TreeNode(rootValue);
39+
root->left = helper(postLeft, postLeft + rootIndex - inLeft - 1, inLeft, rootIndex - 1, postorder, inorder);
40+
root->right = helper(postLeft + rootIndex - inLeft, postRight - 1, rootIndex + 1, inRight, postorder, inorder);
41+
42+
return root;
43+
}
44+
}
45+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# 160ms 81.93%
2+
3+
# Definition for a binary tree node.
4+
# class TreeNode:
5+
# def __init__(self, x):
6+
# self.val = x
7+
# self.left = None
8+
# self.right = None
9+
10+
class Solution:
11+
def buildTree(self, inorder, postorder):
12+
"""
13+
:type inorder: List[int]
14+
:type postorder: List[int]
15+
:rtype: TreeNode
16+
"""
17+
return self.helper(0, len(postorder) - 1, 0, len(inorder) - 1, postorder, inorder)
18+
19+
def helper(self, postLeft, postRight, inLeft, inRight, postorder, inorder):
20+
if postLeft > postRight:
21+
return None
22+
elif postLeft == postRight:
23+
return TreeNode(postorder[postRight])
24+
else:
25+
rootValue = postorder[postRight]
26+
rootIndex = inorder.index(rootValue)
27+
28+
root = TreeNode(rootValue)
29+
root.left = self.helper(postLeft, postLeft + rootIndex - inLeft - 1, inLeft, rootIndex - 1, postorder, inorder)
30+
root.right = self.helper(postLeft + rootIndex - inLeft, postRight - 1, rootIndex + 1, inRight, postorder, inorder)
31+
32+
return root
33+

0 commit comments

Comments
 (0)