Skip to content

Commit

Permalink
[Leetcode] binary-tree-paths
Browse files Browse the repository at this point in the history
  • Loading branch information
ehdgua01 committed Nov 5, 2024
1 parent b31ab82 commit 073136d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
Empty file.
44 changes: 44 additions & 0 deletions coding_test/leetcode/binary_tree_paths/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from typing import List, Optional


class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right


class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
result = []
stack = []

def backtrack(node: TreeNode):
stack.append(node.val)
if node.left is node.right is None:
result.append("->".join(map(str, stack)))
return
if node.left:
backtrack(node.left)
stack.pop()
if node.right:
backtrack(node.right)
stack.pop()

backtrack(root)
return result


def test_binary_tree_paths():
s = Solution()
assert s.binaryTreePaths(TreeNode(1)) == ["1"]
assert s.binaryTreePaths(
TreeNode(
1,
left=TreeNode(
2,
right=TreeNode(5),
),
right=TreeNode(3),
)
) == ["1->2->5", "1->3"]

0 comments on commit 073136d

Please sign in to comment.