Skip to content

Commit 0f0ce63

Browse files
author
Chris Wu
committed
no message
1 parent 3d9c64c commit 0f0ce63

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

problems/binary-tree-paths.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution(object):
2+
def binaryTreePaths(self, root):
3+
if not root: return []
4+
5+
arrow = '->'
6+
7+
ans = []
8+
stack = []
9+
stack.append((root, ''))
10+
11+
while stack:
12+
node, path = stack.pop()
13+
path += arrow+str(node.val) if path else str(node.val) #add arrow except beginnings
14+
if not node.left and not node.right: ans.append(path) #if isLeaf, append path.
15+
if node.left: stack.append((node.left, path))
16+
if node.right: stack.append((node.right, path))
17+
18+
return ans

problems/longest-univalue-path.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution(object):
2+
def longestUnivaluePath(self, root):
3+
def getUnivalueLength(node, val):
4+
if not node: return 0
5+
6+
l, r = getUnivalueLength(node.left, node.val), getUnivalueLength(node.right, node.val)
7+
self.ans = max(self.ans, l+r)
8+
9+
if node.val==val: return 1+max(l, r)
10+
return 0
11+
12+
if not root: return 0
13+
self.ans = float('-inf')
14+
getUnivalueLength(root, root.val)
15+
return self.ans
16+
17+
"""
18+
The main I idea is simple.
19+
Traverse all the node.
20+
Each node, we assume that the longestUnivaluePath will pass through it.
21+
So we can update the `self.ans` if `l+r` is larger.
22+
At the same time, `getUnivalueLength()` will return the max length of the path (start from itself) which has the value `val`.
23+
"""

0 commit comments

Comments
 (0)