Last active
November 27, 2018 18:11
-
-
Save pohzipohzi/cc000880ab4eb49ea25173816898ad23 to your computer and use it in GitHub Desktop.
Recursive and iterative implementations of basic tree traversals in python 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TreeNode: | |
def __init__(self, val): | |
self.val = val | |
self.left = None | |
self.right = None | |
def buildTree(arr): | |
nodes = [TreeNode(val) for val in arr] | |
for i in range(len(nodes)): | |
left, right = (i+1)*2-1, (i+1)*2 | |
if left < len(arr): | |
nodes[i].left = nodes[left] | |
if right < len(arr): | |
nodes[i].right = nodes[right] | |
return nodes[0] | |
def preorderRecursive(node): | |
if node is None: | |
return [] | |
return [node.val] + preorderRecursive(node.left) + preorderRecursive(node.right) | |
def preorderIterative(node): | |
res, stack = [], [(1, node)] # flag, node | |
while len(stack) > 0: | |
flag, node = stack.pop() | |
if node is not None: | |
if flag == 0: | |
res.append(node.val) | |
else: | |
stack.extend([(1, node.right), (1, node.left), (0, node)]) | |
return res | |
def inorderRecursive(node): | |
if node is None: | |
return [] | |
return inorderRecursive(node.left) + [node.val] + inorderRecursive(node.right) | |
def inorderIterative(node): | |
res, stack = [], [(1, node)] # flag, node | |
while len(stack) > 0: | |
flag, node = stack.pop() | |
if node is not None: | |
if flag == 0: | |
res.append(node.val) | |
else: | |
stack.extend([(1, node.right), (0, node), (1, node.left)]) | |
return res | |
def postorderRecursive(node): | |
if node is None: | |
return [] | |
return postorderRecursive(node.left) + postorderRecursive(node.right) + [node.val] | |
def postorderIterative(node): | |
res, stack = [], [(1, node)] # flag, node | |
while len(stack) > 0: | |
flag, node = stack.pop() | |
if node is not None: | |
if flag == 0: | |
res.append(node.val) | |
else: | |
stack.extend([(0, node), (1, node.right), (1, node.left)]) | |
return res | |
if __name__ == "__main__": | |
head = buildTree([1,2,3,4,5,6,7]) | |
print(preorderRecursive(head)) # [1, 2, 4, 5, 3, 6, 7] | |
print(preorderIterative(head)) # [1, 2, 4, 5, 3, 6, 7] | |
print(inorderRecursive(head)) # [4, 2, 5, 1, 6, 3, 7] | |
print(inorderIterative(head)) # [4, 2, 5, 1, 6, 3, 7] | |
print(postorderRecursive(head)) # [4, 5, 2, 6, 7, 3, 1] | |
print(postorderIterative(head)) # [4, 5, 2, 6, 7, 3, 1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment