Skip to content

Commit da1fca3

Browse files
authored
Merge pull request #170 from dsrao711/issue_169
Python solution for Post order reversal, iterative and recursive
2 parents b51c914 + e1db341 commit da1fca3

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

DSA 450 GFG/post-ord-iterative.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
2+
# https://leetcode.com/problems/binary-tree-postorder-traversal/
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+
class Solution:
11+
def postorderTraversal(self, root: TreeNode) -> List[int]:
12+
13+
if root == None:
14+
return
15+
16+
stack = deque()
17+
stack.append(root)
18+
19+
# create another stack to store postorder traversal
20+
out = deque()
21+
22+
# loop till stack is empty
23+
while stack:
24+
25+
# pop a node from the stack and push the data into the output stack
26+
curr = stack.pop()
27+
out.append(curr.val)
28+
29+
# push the left and right child of the popped node into the stack
30+
if curr.left:
31+
stack.append(curr.left)
32+
33+
if curr.right:
34+
stack.append(curr.right)
35+
36+
out.reverse()
37+
38+
return out

DSA 450 GFG/post-order-rec.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#https://www.hackerrank.com/challenges/tree-postorder-traversal/problem
2+
3+
class Node:
4+
def __init__(self, info):
5+
self.info = info
6+
self.left = None
7+
self.right = None
8+
self.level = None
9+
10+
def __str__(self):
11+
return str(self.info)
12+
13+
class BinarySearchTree:
14+
def __init__(self):
15+
self.root = None
16+
17+
def create(self, val):
18+
if self.root == None:
19+
self.root = Node(val)
20+
else:
21+
current = self.root
22+
23+
while True:
24+
if val < current.info:
25+
if current.left:
26+
current = current.left
27+
else:
28+
current.left = Node(val)
29+
break
30+
elif val > current.info:
31+
if current.right:
32+
current = current.right
33+
else:
34+
current.right = Node(val)
35+
break
36+
else:
37+
break
38+
39+
"""
40+
Node is defined as
41+
self.left (the left child of the node)
42+
self.right (the right child of the node)
43+
self.info (the value of the node)
44+
"""
45+
def postOrder(root):
46+
#Write your code here
47+
if root :
48+
postOrder(root.left)
49+
postOrder(root.right)
50+
print(str(root.info) + " " , end = "")

0 commit comments

Comments
 (0)