Created
August 4, 2021 19:24
-
-
Save o-az/da558a8bf6a0481dff3d924ec8848568 to your computer and use it in GitHub Desktop.
DFS Binary Tree Traversal – Inorder, Postorder, and Preorder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self, key): | |
self.left = None | |
self.right = None | |
self.value = key | |
def inOrder(root, visited=[]): | |
if root is not None: | |
inOrder(root.left, visited) | |
visited.append(root.value) | |
inOrder(root.right, visited) | |
return visited | |
def postOrder(root, visited=[]): | |
if root is not None: | |
postOrder(root.left, visited) | |
postOrder(root.right, visited) | |
visited.append(root.value) | |
return visited | |
def preOrder(root, visited=[]): | |
if root is not None: | |
visited.append(root.value) | |
preOrder(root.left, visited) | |
preOrder(root.right, visited) | |
return visited | |
""" | |
Binary Tree Example: | |
1 | |
/ \ | |
2 3 | |
/ \ / \ | |
4 5 6 7 | |
/ \ | |
8 9 | |
""" | |
root = Node(1) | |
root.left = Node(2) | |
root.right = Node(3) | |
root.left.left = Node(4) | |
root.left.right = Node(5) | |
root.right.left = Node(6) | |
root.right.right = Node(7) | |
root.left.left.left = Node(8) | |
root.left.left.right = Node(9) | |
traversalExamples = { | |
"inOrder": inOrder(root), | |
"postOrder": postOrder(root), | |
"preOrder": preOrder(root), | |
} | |
import json | |
print(json.dumps(traversalExamples, indent=2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment