Skip to content

Commit 873b93f

Browse files
committed
257
1 parent 52ac606 commit 873b93f

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,4 @@ Success is like pregnancy, Everybody congratulates you but nobody knows how many
8989
|-----|-------| -------- | ---- | ------|------------|---|-----|
9090
|108|[Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/#/solutions)| [Python [Yu]](./tree/Yu/108.py) | _O(N)_| _O(N)_ | Easy | |[公瑾讲解](https://www.youtube.com/watch?v=lBrb4fXPcMM)|
9191
|563|[Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/#/description)| [Python [Yu]](./tree/Yu/563.py) | _O(N)_| _O(1)_ | Easy | |[公瑾讲解](https://youtu.be/47FQVP4ynk0)|
92+
|257|[Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/#/description)| [Python [Yu]](./tree/Yu/257.py) | _O(N)_| _O(N)_ | Easy | |[公瑾讲解](https://youtu.be/Zr_7qq2f16k)|

tree/Yu/257.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
3+
4+
# Author: Yu Zhou
5+
6+
# 257. Binary Tree Paths
7+
8+
# 思路:
9+
# DFS + Stack
10+
11+
class Solution(object):
12+
def binaryTreePaths(self, root):
13+
"""
14+
:type root: TreeNode
15+
:rtype: List[str]
16+
"""
17+
stack = [(root, "")]
18+
res = []
19+
20+
# Edge Case
21+
if not root:
22+
return []
23+
24+
# res: ["1->3", "1->2->5"]
25+
while stack:
26+
node, strr = stack.pop()
27+
if not node.left and not node.right:
28+
res.append(strr + str(node.val))
29+
if node.left:
30+
stack.append((node.left, strr + str(node.val) + "->"))
31+
if node.right:
32+
stack.append((node.right, strr + str(node.val) + "->"))
33+
return res

0 commit comments

Comments
 (0)