Skip to content

Instantly share code, notes, and snippets.

@liyunrui
Last active May 30, 2021 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liyunrui/731b834dcd2b03b9526d27f699c0cb29 to your computer and use it in GitHub Desktop.
Save liyunrui/731b834dcd2b03b9526d27f699c0cb29 to your computer and use it in GitHub Desktop.
leetcode-bt
"""
Given a bst
5
/ \
3 7
/ \ /
1 4 6
pre-order: 5-> 3 -> 7 ==> 5->3->1->4->7->6
/ \ /
1 4 6
post-order: 3 -> 7 -> 5 ==> 1->4->3->6->7->5
/ \ /
1 4 6
in-order: 3 -> 5 -> 7 ==> 1->3->4->5->6->7
/ \ /
1 4 6
"""
def preorder(root):
"""root -> left subtree -> right subtree"""
if not root:
return
print (root.val)
preorder(root.left)
preorder(root.right)
def postorder(root):
"""left subtree -> right subtree -> root"""
if not root:
return
postorder(root.left)
postorder(root.right)
print (root.val)
def inorder(root):
"""left subtree -> root -> right subtree"""
if not root:
return
inorder(root.left)
print (root.val)
inorder(root.right)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment