Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit de93113

Browse files
Binary Tree Paths
1 parent 9689153 commit de93113

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

‎257-binary-tree-paths.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/binary-tree-paths/
3+
4+
Given the root of a binary tree, return all root-to-leaf paths in any order.
5+
A leaf is a node with no children.
6+
7+
Example 1:
8+
9+
Input: root = [1,2,3,null,5]
10+
Output: ["1->2->5","1->3"]
11+
12+
Example 2:
13+
Input: root = [1]
14+
Output: ["1"]
15+
16+
Constraints:
17+
The number of nodes in the tree is in the range [1, 100].
18+
-100 <= Node.val <= 100
19+
"""
20+
# Definition for a binary tree node.
21+
# class TreeNode:
22+
# def __init__(self, val=0, left=None, right=None):
23+
# self.val = val
24+
# self.left = left
25+
# self.right = right
26+
class Solution:
27+
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
28+
if not root:
29+
return []
30+
return self.helper(root, [], [])
31+
32+
def helper(self, root, res, cur_path):
33+
if not root:
34+
return res
35+
36+
cur_path.append(str(root.val))
37+
if not root.left and not root.right:
38+
res.append("->".join(cur_path))
39+
40+
self.helper(root.left, res, cur_path)
41+
self.helper(root.right, res, cur_path)
42+
cur_path.pop()
43+
return res

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /