Question & Answer: Write an function to output a Binary Search Tree in-order iteratively instead of recursively……

Write an function to output a Binary Search Tree in-order iteratively instead of recursively.

Expert Answer

 

# Python code to do inorder traversal without recursion

# tree Treenode

class TreeNode:

def __init__(self, data):

self.data = data

self.left = None

self.right = None

# inorder tree traversal iterative function

def inorderTraversal(rootTreeNode):

currentTreeNode = rootTreeNode

stackS = []

finished = 0

while(not finished):

if currentTreeNode is not None:

stackS.append(currentTreeNode)

currentTreeNode = currentTreeNode.left

else:

if(len(stackS) >0 ):

currentTreeNode = stackS.pop()

print currentTreeNode.data,

currentTreeNode = currentTreeNode.right

else:

finished = 1

# Driver code

rootTreeNode = TreeNode(1)

rootTreeNode.left = TreeNode(2)

rootTreeNode.right = TreeNode(3)

rootTreeNode.left.left = TreeNode(4)

rootTreeNode.left.right = TreeNode(5)

inorderTraversal(rootTreeNode)

Question & Answer: Write an function to output a Binary Search Tree in-order iteratively instead of recursively...... 1

Still stressed from student homework?
Get quality assistance from academic writers!