logo头像
Snippet 博客主题

【Leetcode 257】Binary Tree Paths

难度: 简单(Easy)

题目

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

1
/
2 3

5
All root-to-leaf paths are:

[“1->2->5”, “1->3”]

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):

def visit(self, root, cur_path, pathes):
cur_path.append(root.val)
if root.left==None and root.right==None:
pathes.append('->'.join([str(n) for n in cur_path]))
else:
if root.left != None:
self.visit(root.left, cur_path, pathes)
if root.right != None:
self.visit(root.right, cur_path, pathes)
cur_path.pop()

def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if root == None:
return []
res = []
self.visit(root,[],res)
return res

评论系统未开启,无法评论!