Question: Write code to implement a function that will compute the height of a tree. Call the function treeHeight(root). Test your code with at least three
Write code to implement a function that will compute the height of a tree. Call the function treeHeight(root). Test your code with at least three trees that you can create using expressions and the buildParseTree function. Make sure to make it a Driver so you can see the program print something out.
here is the buildParseTree function:
from pythonds.basic.stack import Stack from pythonds.trees.binaryTree import BinaryTree
def buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i not in ['+', '-', '*', '/', ')']: currentTree.setRootVal(int(i)) parent = pStack.pop() currentTree = parent elif i in ['+', '-', '*', '/']: currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: raise ValueError return eTree
pt = buildParseTree("( ( 10 + 5 ) * 3 )") pt.postorder() #defined and explained in the next section
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
