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
|
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
|