Skip to content

Commit 7a6ba0f

Browse files
committed
Feb 23
1 parent 2848c58 commit 7a6ba0f

File tree

2 files changed

+56
-2
lines changed

2 files changed

+56
-2
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
from typing import List, Optional
2+
3+
4+
# Definition for a binary tree node.
5+
class TreeNode:
6+
def __init__(self, val=0, left=None, right=None):
7+
self.val = val
8+
self.left = left
9+
self.right = right
10+
11+
12+
class Solution:
13+
def constructFromPrePost(
14+
self, preorder: List[int], postorder: List[int]
15+
) -> Optional[TreeNode]:
16+
root = TreeNode(preorder[0])
17+
stack = [root]
18+
pre_index, post_index = 1, 0
19+
while stack:
20+
node = stack[-1]
21+
if node.val == postorder[post_index]:
22+
stack.pop()
23+
post_index += 1
24+
else:
25+
new_node = TreeNode(preorder[pre_index])
26+
pre_index += 1
27+
if node.left is None:
28+
node.left = new_node
29+
else:
30+
node.right = new_node
31+
stack.append(new_node)
32+
return root
33+
34+
35+
def main():
36+
preorder = [1, 2, 4, 5, 3, 6, 7]
37+
postorder = [4, 5, 2, 6, 7, 3, 1]
38+
root = Solution().constructFromPrePost(preorder, postorder)
39+
assert root.val == 1
40+
assert root.left.val == 2
41+
assert root.right.val == 3
42+
assert root.left.left.val == 4
43+
assert root.left.right.val == 5
44+
assert root.right.left.val == 6
45+
assert root.right.right.val == 7
46+
47+
preorder = [1]
48+
postorder = [1]
49+
root = Solution().constructFromPrePost(preorder, postorder)
50+
assert root.val == 1
51+
52+
53+
if __name__ == '__main__':
54+
main()

2025-02-February-LeetCoding-Challenge/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
| February 20 | [1980. Find Unique Binary String](https://leetcode.com/problems/find-unique-binary-string/) | Medium | Solved |
2727
| February 21 | [1261. Find Elements in a Contaminated Binary Tree](https://leetcode.com/problems/find-elements-in-a-contaminated-binary-tree/) | Medium | Solved |
2828
| February 22 | [1028. Recover a Tree From Preorder Traversal](https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/) | Hard | Solved |
29-
| February 23 | []() | | |
29+
| February 23 | [889. Construct Binary Tree from Preorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/) | Medium | Unsolved |
3030
| February 24 | []() | | |
3131
| February 25 | []() | | |
3232
| February 26 | []() | | |
@@ -38,5 +38,5 @@
3838
| Level | Problems | Solved | Unsolved |
3939
| --- | --- | --- | --- |
4040
| Easy | 6 | 6 | 0 |
41-
| Medium | 14 | 11 | 3 |
41+
| Medium | 15 | 12 | 3 |
4242
| Hard | 1 | 1 | 0 |

0 commit comments

Comments
 (0)