Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inorder_Preorder_Postorder_Tree_Traversal in python #2107

Merged
merged 1 commit into from
Oct 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified Program's_Contributed_By_Contributors/Java_Programs/.DS_Store
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Python program for inorder,preorder and postorder tree traversals

# Making Node
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key


# A function for inorder tree traversal
def printInorder(root):

if root:

# First recur on left child
printInorder(root.left)

# then print the data of node
print(root.val, end=" "),

# now recur on right child
printInorder(root.right)

# A function for preorder tree traversal


def printPreorder(root):

if root:

# First print the data of node
print(root.val, end=" "),

# Then recur on left child
printPreorder(root.left)

# Finally recur on right child
printPreorder(root.right)

# A function for 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, end=" "),


# Driver code
if __name__ == "__main__":
root = Node(1)
root.left = Node(2)
root.right = Node(7)
root.left.left = Node(6)
root.left.right = Node(5)

# 1
# / \
# 2 7
# / \
# 6 5


print("\nInorder traversal of binary tree: ")
printInorder(root)
print("\nPreorder traversal of binary tree: ")
printPreorder(root)
print("\nPostorder traversal of binary tree: ")
printPostorder(root)
print("\n")