def ParseTree(exp): exp = exp.split() expTree = BinaryTree('') # create an empty tree parents = Stack() # create stack to hold the parents parents.push(expTree) # root is kept on bttm of stack for item in exp: if item == '(': # next item will be var or int, followed by an operator - we need to move down expTree.insertLeft( '' ) # insert empty node on left which will be a num or int later parents.push(expTree) expTree = expTree.getLeftChild( ) # move down so num or var can be placed elif item == ')': expTree = parents.pop() elif item in OPERATORS: expTree.key = item # operator is placed at current node expTree.insertRight('') parents.push(expTree) expTree = expTree.getRightChild( ) # we move right because a symbol or an num must be placed next elif item not in SYMBOLS and item not in OPERATORS and item != "(" and item != ")": expTree.key = float( item ) # entering them as float in case anyone inputs float values expTree = parents.pop() elif item in SYMBOLS: expTree.key = item expTree = parents.pop() return expTree
# _*_ coding: utf-8 -*- # @Time : 8/27/20 3:19 PM # @Author : title_z # @Filename : Binarytree.py from pythonds.trees import BinaryTree # r = BinaryTree(3) # BinaryTree.insertLeft(r, 4) # BinaryTree.insertLeft(r, 5) # BinaryTree.insertRight(r, 6) # BinaryTree.insertRight(r, 7) # l = BinaryTree.getLeftChild(r) # print(l) r = BinaryTree('a') r.insertLeft('b') r.insertRight('c') r.getRightChild().setRootVal('hello') r.getLeftChild().insertRight('d') print(r)
# 3. Using the findSuccesor method, write a non-recursive inorder traversal for a binary search tree. from pythonds.basic import Stack from pythonds.trees import BinaryTree # Inorder traversal using a Stack def inorderTrav(tree): posStack = Stack() current = tree while current != None or posStack.size() > 0: # Left-most node while (current != None): posStack.push(current) current = current.getLeftChild() current = posStack.pop() print(current.getRootVal()) current = current.getRightChild() tree = BinaryTree("A") tree.insertLeft("B") tree.getLeftChild().insertLeft("C") tree.getLeftChild().insertRight("D") tree.insertRight("E") inorderTrav(tree)
else: return tree.getRootVal() # 还原完全括号表达式 def printExp(tree): sumVal = '' if tree: currentVal = tree.getRootVal() if isinstance(currentVal, int): sumVal = printExp(tree.getLeftChild()) else: sumVal = '(' + printExp(tree.getLeftChild()) sumVal = sumVal + str(tree.getRootVal()) if isinstance(currentVal, int): sumVal = sumVal + printExp(tree.getRightChild()) else: sumVal = sumVal + printExp(tree.getRightChild()) + ')' return sumVal etree = BinaryTree('*') etree.insertRight(2) etree.insertLeft(3) preorder(etree) print(printExp(etree)) print(postorderEval(etree))