-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinaryInorderTraversalLeet94.py
62 lines (53 loc) · 1.76 KB
/
binaryInorderTraversalLeet94.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import queue
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BinaryTree:
def __init__(self,nodes=None):
nodeQueue = queue.Queue()
if nodes is None:
self.root = None
else:
node = TreeNode(nodes[1])
self.root = node
for i in range(2,len(nodes)):
if i%2 == 0:
left = TreeNode(nodes[i])
node.left = left
nodeQueue.put(left)
else:
right = TreeNode(nodes[i])
node.right = right
nodeQueue.put(right)
node = nodeQueue.get()
def inorderTraversal(root):
# Recursive solution
result = []
def recursiveInOrder(root):
if root == None:
return
else:
recursiveInOrder(root.left)
result.append(root.val)
recursiveInOrder(root.right)
return
recursiveInOrder(root)
return result
# Solution suggested by a user in JAVA is translated to python, iterative
# result = []
# nodeList = []
# currentNode = root
# while currentNode != None or bool(nodeList):
# while currentNode != None:
# nodeList.append(currentNode)
# currentNode = currentNode.left
# currentNode = nodeList.pop()
# result.append(currentNode.val)
# currentNode = currentNode.right
# return result
if __name__ == "__main__":
nodes = [0,3,1,2,4,9,10,None,5,6]
binaryTree = BinaryTree(nodes)
print(inorderTraversal(binaryTree.root))