'Display postOrderBefore(v) and postOrderAfter(v) in perfect binary tree, without using tree traversal methods(inOrder, PostOrder and preOrder)
For example, Take n nodes from user and target element v. input = [1,2,3,4,5,6,7] where 1 is root. 2 & 3 are left and right child of 1. 4 & 5 are left & right child of 2. 6 & 7 are left & right child of 3.
if user give input v as 5 -> program should display 4 and 2 as output. Since, postOrder of the given binary tree will be -> [4,5,2,6,7,3,1]. Here postOrderBefore is 4 and postOrderAfter is 2 when v = 5.
Write a pseudo-code to find out before and after element of v. Also, calculate running time of code.
My code:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
# A function to do postorder tree traversal
def printPostorder(root):
if root:
# First recur on left child
printPostorder(root.left)
# the recur on right child
printPostorder(root.right)
# now print the data of node
print(root.val),
print("Enter number of nodes: ")
n = int(input())
list = []
print("Enter nodes: ")
for i in range(0, n):
ele = int(input())
list.append(ele)
for i in range(0, n):
print("\n",list[i])
for i in range(0, n):
root = Node(list[i])
root.left = Node(list[i+1])
root.right = Node(list[i+2])
root.left.left = Node(list[i+3])
root.left.right = Node(list[i+4])
root.right.left = Node(list[i+5])
root.right.right = Node(list[i+6])
break
print ("\nPostorder traversal of binary tree is")
printPostorder(root)
Here n is 7.
Solution 1:[1]
postorderBefore(v):
if v.right! = None:
return v.right.data
else:
node = v.parent
if node.right = v:
return node.left.data
else:
while node!= None AND v == node.left:
v = node
node = node.parent
if node == None:
return node.data
else
return node.left.data
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Elon Power |
