add some fun tree playing

This commit is contained in:
bt3gl 2023-07-29 14:28:17 -07:00 committed by GitHub
parent 48720ada4d
commit bb72bab679
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 209 additions and 0 deletions

View file

@ -0,0 +1,28 @@
# recursive and iterative inorder traversal
def preorder_recursive(root: Optional[TreeNode]) -> list[int]:
if root == None:
return []
return [root.val] + preorder_recursive(root.left) + preorder_recursive(root.right)
def preorder_iterative(root: Optional[TreeNode]) -> list[int]:
result = []
stack = [root]
while stack:
current = stack.pop()
result.append(current.val)
if current.right:
stack.append(current.right)
if current.left:
stack.append(current.left)
return result