I'm looking for some help with the Preorder Traversal problem. This is the code that I came up with. It passes test one (Input: [1, null, 2, 3], Output: [1, 2, 3]), but fails test two (Input: [], Output: [1, 2, 3], Expected: [])
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode, result=[]):
if root:
result.append(root.val)
self.preorderTraversal(root.left, result)
self.preorderTraversal(root.right, result)
return resultHowever, I found the code below that another user had come up with and it passes all the tests.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def transverse(self, node, content):
if node:
content.append(node.val)
self.transverse(node.left, content)
self.transverse(node.right, content)
return content
def preorderTraversal(self, root: TreeNode) -> List[int]:
return self.transverse(root, [])To me, these two solutions look the same and when I test them, I get the same output, so I don't understand why my code is failing. If anyone could help, I would appreciate it.