From a199d158d58df1dc9035d386bc88eb1741408296 Mon Sep 17 00:00:00 2001 From: Deven <63876261+devenperez@users.noreply.github.com> Date: Mon, 9 Jan 2023 18:33:51 -0500 Subject: [PATCH] Time: 32 ms (84.16%), Space: 13.9 MB (56.74%) - LeetHub --- .../144-binary-tree-preorder-traversal.py | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 144-binary-tree-preorder-traversal/144-binary-tree-preorder-traversal.py diff --git a/144-binary-tree-preorder-traversal/144-binary-tree-preorder-traversal.py b/144-binary-tree-preorder-traversal/144-binary-tree-preorder-traversal.py new file mode 100644 index 0000000..1c33a45 --- /dev/null +++ b/144-binary-tree-preorder-traversal/144-binary-tree-preorder-traversal.py @@ -0,0 +1,30 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + # Base cases: no node or only root node + if root == None: + return [] + + if root.left == None and root.right == None: + return [root.val] + + # Simple recursive solution: add to array as you traverse + visited = [root.val] # First node in the order is the current one + + # All nodes to the left must be added next in the array + if root.left != None: + visited += self.preorderTraversal(root.left) + + # All nodes to the right must be added next in the array + if root.right != None: + visited += self.preorderTraversal(root.right) + + return visited + + + \ No newline at end of file