Pre-Order Traversal
In this lesson, we will cover the traversal strategy, 'Pre-Order Traversal' in a Binary Search Tree, and its implementation it in Python
We'll cover the following...
Introduction #
In this traversal, the elements are traversed in “root-left-right” order. We first visit the root/parent node, then the left child, and then the right child. Here is a high-level description of the algorithm for Pre-Order traversal, starting from the root node:
-
Visit the current node, i.e., print the value stored at the node
-
Call the
preOrderPrint()
function on the left sub-tree of the ‘current Node’. -
Call the
preOrderPrint()
function on the right sub-tree of the ‘current Node’.
Implementation in Python
...Press + to interact
main.py
BinarySearchTree.py
Node.py
from Node import Nodefrom BinarySearchTree import BinarySearchTreedef preOrderPrint(node):if node is not None:print(node.val)preOrderPrint(node.leftChild)preOrderPrint(node.rightChild)BST = BinarySearchTree(6)BST.insert(4)BST.insert(9)BST.insert(5)BST.insert(2)BST.insert(8)BST.insert(12)preOrderPrint(BST.root)
...
Access this course and 1400+ top-rated courses and projects.