0%

leetcode 刷题总结

leetcode 刷题总结

题目描述
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。

示例
输入:
1
/ \
2 3
\
5
输出: [“1->2->5”, “1->3”]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

递归方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
def gen(root, path):
if root: # 当前节点存在
path += str(root.val)
if not root.left and not root.right: # 当前节点是叶子节点
paths.append(path)
else:
path += '->' #当前节点不是叶子节点,继续递归遍历
gen(root.left, path)
gen(root.right, path)
paths = []
gen(root, '')
return paths

非递归方法

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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
paths = []
if not root:
return paths
nodedeq = collections.deque([root])
pathdeq = collections.deque([str(root.val)])
while nodedeq:
node = nodedeq.popleft()
path = pathdeq.popleft()

if not node.left and not node.right:
paths.append(path)
else:
if node.left:
nodedeq.append(node.left)
pathdeq.append(path + '->' + str(node.left.val))
if node.right:
nodedeq.append(node.right)
pathdeq.append(path + '->' + str(node.right.val))
return paths
-------------Thanks for your attention-------------