Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! π»π₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! π
100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney
Problem:
https://www.geeksforgeeks.org/problems/construct-tree-from-preorder-postorder/1
Construct Tree from Preorder & Postorder
Difficulty: Medium Accuracy: 88.3%
Given two arrays pre[] and post[] that represent the preorder and postorder traversals of a full binary tree. Your task is to construct the binary tree and return its root.
Note: Full Binary Tree is a binary tree where every node has either 0 or 2 children. The preorder and postorder traversals contain unique values, and every value present in the preorder traversal is also found in the postorder traversal.
Examples:
Input: pre[] = [1, 2, 4, 8, 9, 5, 3, 6, 7], post[] = [8, 9, 4, 5, 2, 6, 7, 3, 1]
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Explanation: The tree will look like
Input: pre[] = [1, 2, 4, 5, 3, 6, 7] , post[] = [4, 5, 2, 6, 7, 3, 1]
Output: [1, 2, 3, 4, 5, 6, 7]
Explanation: The tree will look like
Constraints:
1 β€ number of nodes β€ 103
1 β€ pre[i], post[i] β€ 104
Solution:
class Node:
def init(self, val):
self.data = val
self.left = None
self.right = None
class Solution:
def constructTree(self, pre, post):
self.index = 0
n = len(pre)
post_index = {val: i for i, val in enumerate(post)}
def build(l, r):
if self.index >= n or l > r:
return None
root = Node(pre[self.index])
self.index += 1
if l == r or self.index >= n:
return root
mid = post_index[pre[self.index]]
root.left = build(l, mid)
root.right = build(mid + 1, r - 1)
return root
return build(0, n - 1)
Top comments (0)