Last active
April 3, 2020 02:44
-
-
Save nhudinhtuan/d13e84f4bd0348eef32495e0201f5a98 to your computer and use it in GitHub Desktop.
Tree traversal - Preorder
This file contains hidden or 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
# Definition for a binary tree node. | |
# class TreeNode(object): | |
# def __init__(self, x): | |
# self.val = x | |
# self.left = None | |
def preorder_traversal_recursive(root): | |
result = [] | |
def recur(node): | |
# base case | |
if not node: | |
return | |
# visit node | |
result.append(node.val) | |
# traverse the left subtree | |
recur(node.left) | |
# traverse the right subtree | |
recur(node.right) | |
recur(root) | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment