Programming in python: BFS in python from a preorder and inorder on newest questions tagged python – Stack Overflow

(Python 2.7)I need to print the bfs of a binary tree with a given preorder and inorder and a max lenght of the strings of preorder and inorder.
I know how it works, for example:
preorder:ABCDE
inorder:CBDAE
max length:5

                A
             /     \
           B        E
          / \
         C   D

BFS:ABECD

So far I got this figured out

class BinaryTree:
    def __init__ (self, value, parent=None):
            self.parent = parent
            self.left_child = None
            self.right_child = None
            self.value=value

    def setLeftChild(self, child=None):
            self.left_child = child
            if child:
                child.parent = self

    def setRightChild(self, child=None):
            self.right_child = child
            if child:
                child.parent = self

preorder=[]
inorder=[]

print "max string length?"
i=int(raw_input())
count=0
while i>count:
    print"insert the preorder"
    preorder.append(raw_input())
    count=count+1
print "preorder is",preorder

count2=0
while i>count2:
    print"insert the inorder"
    inorder.append(raw_input())
    count2=count2+1
print "inorder is",inorder
root=BinaryTree(preorder[0])
print root.value
root.setLeftChild(BinaryTree(preorder[1]))
print root.left_child.value
raw_input()

I’ve figured out how to create a binary tree in python but the thing is I don’t know how to add the values of the next childs. As you can see I already have the root and figured out how to insert the first childs (left and right) but I don’t know how to add the next ones.

See Answers


source: http://stackoverflow.com/questions/11174997/bfs-in-python-from-a-preorder-and-inorder
Programming in python: programming-in-python



online applications demo