mirror of
https://github.com/yangshun/tech-interview-handbook.git
synced 2025-07-28 20:52:00 +08:00
misc: restructure contents
This commit is contained in:
62
experimental/utilities/python/tree_traversal.py
Normal file
62
experimental/utilities/python/tree_traversal.py
Normal file
@ -0,0 +1,62 @@
|
||||
# Various iterative ways of traversing a tree.
|
||||
def inorder_traversal(root):
|
||||
"""
|
||||
:type root: TreeNode
|
||||
:rtype: List[int]
|
||||
"""
|
||||
if not root:
|
||||
return []
|
||||
result = []
|
||||
stack = [root]
|
||||
while len(stack) > 0:
|
||||
curr_node = stack.pop()
|
||||
if curr_node.left:
|
||||
stack.append(curr_node)
|
||||
stack.append(curr_node.left)
|
||||
curr_node.left = None
|
||||
else:
|
||||
result.append(curr_node.val)
|
||||
if curr_node.right:
|
||||
stack.append(curr_node.right)
|
||||
return result
|
||||
|
||||
def preorder_traversal(root):
|
||||
"""
|
||||
:type root: TreeNode
|
||||
:rtype: List[int]
|
||||
"""
|
||||
if not root:
|
||||
return []
|
||||
result = []
|
||||
stack = [root]
|
||||
while len(stack) > 0:
|
||||
curr_node = stack.pop()
|
||||
result.append(curr_node.val)
|
||||
if curr_node.right:
|
||||
stack.append(curr_node.right)
|
||||
if curr_node.left:
|
||||
stack.append(curr_node.left)
|
||||
return result
|
||||
|
||||
def postorder_traversal(root):
|
||||
"""
|
||||
:type root: TreeNode
|
||||
:rtype: List[int]
|
||||
"""
|
||||
if not root:
|
||||
return []
|
||||
result = []
|
||||
stack = [root]
|
||||
while len(stack) > 0:
|
||||
curr_node = stack.pop()
|
||||
if curr_node.left:
|
||||
stack.append(curr_node)
|
||||
stack.append(curr_node.left)
|
||||
curr_node.left = None
|
||||
elif curr_node.right:
|
||||
stack.append(curr_node)
|
||||
stack.append(curr_node.right)
|
||||
curr_node.right = None
|
||||
else:
|
||||
result.append(curr_node.val)
|
||||
return result
|
Reference in New Issue
Block a user