inorder traversal python

Solutions on MaxInterview for inorder traversal python by the best coders in the world

showing results for - "inorder traversal python"
Antony
13 Jan 2020
1class Binarytree:
2    def __init__(self,data):
3        self.data = data
4        self.left = None
5        self.right = None
6    
7    def addChild(self, data):
8        if data == self.data:
9            return
10        
11        if data < self.data:
12            if self.left:
13                self.left.addChild(data)
14            else:
15                self.left = Binarytree(data)
16        else:
17            if self.right:
18                self.right.addChild(data)
19            else:
20                self.right = Binarytree(data)
21                
22    # Inorder traversal
23    def inorder(self):
24        element = [ ]
25        
26        if self.left:
27            element += self.left.inorder()
28        
29        element.append(self.data)
30        
31        if self.right:
32            element += self.right.inorder()
33        
34        return element
35
36def buildtree(element):
37    root = Binarytree(element[0])
38    for i in range(1,len(element)):
39        root.addChild(element[i])
40    return root
41    
42if __name__ == '__main__':
43    element = [39, 87, 21, 42, 95, 52, 12]
44    tree = buildtree(element)
45    print(tree.inorder())