I created Binary Tree with some nodes and trying to get the result of inorder traversal using dictionary, but It does not really work. Why the list does not append, even tho it prints the result?
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inoder(bomj):
visited = []
if bomj:
inoder(bomj.left)
print(bomj.val)
visited.append(bomj.val)
inoder(bomj.right)
return visited
tree = TreeNode(1)
tree.left = TreeNode(2)
tree.right = TreeNode(3)
tree.left.left = TreeNode(4)
tree.left.right = TreeNode(5)
tree.left.left.left = TreeNode(7)
tree.right.left = TreeNode(6)
print(inoder(tree))
Result:
7
4
2
5
1
6
3
[1]
I also tried using dictionary
You are resetting
internalevery time you callinorder. You need a variableinorderthat's outside the recursion.