Skip to content

Commit 0df8517

Browse files
solves binary tree paths in python
1 parent 18cb51b commit 0df8517

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@
7777
| 246 | 🔒 [Strobogramatic Number](https://leetcode.com/problems/strobogrammatic-number) | Easy | |
7878
| 252 | 🔒 [Meeting Rooms](https://leetcode.com/problems/meeting-rooms) | Easy | |
7979
| 256 | 🔒 [Paint House](https://leetcode.com/problems/paint-house) | Easy | |
80-
| 257 | [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/BinaryTreePaths.java) |
80+
| 257 | [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/BinaryTreePaths.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/binary_tree_paths.py) |
8181
| 258 | [Add Digits](https://leetcode.com/problems/add-digits) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/AddDigits.java) |
8282
| 263 | [Ugly Number](https://leetcode.com/problems/ugly-number) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/UglyNumber.java) |
8383
| 266 | [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation) | Easy | |

python/binary_tree_paths.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from typing import List
2+
3+
4+
# Definition for a binary tree node.
5+
class TreeNode:
6+
def __init__(self, val=0, left=None, right=None):
7+
self.val = val
8+
self.left = left
9+
self.right = right
10+
11+
12+
class Solution:
13+
def is_leaf_node(self, root: TreeNode) -> bool:
14+
return root.left is None and root.right is None
15+
16+
def binary_tree_paths(self, root: TreeNode, current_path: str, results: List[str]):
17+
if root is None:
18+
return
19+
if self.is_leaf_node(root):
20+
results.append(f'{current_path}->{root.val}'[2:])
21+
return
22+
self.binary_tree_paths(root.left, f'{current_path}->{root.val}', results)
23+
self.binary_tree_paths(root.right, f'{current_path}->{root.val}', results)
24+
25+
def binaryTreePaths(self, root: TreeNode) -> List[str]:
26+
result = []
27+
self.binary_tree_paths(root, '', results=result)
28+
return result

0 commit comments

Comments
 (0)