题目链接
https://leetcode.cn/problems/binary-tree-paths/
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def traversal(self, node, result, path):
path.append(node.val)
if not node.left and not node.right:
spath = '->'.join(map(str, path))
result.append(spath)
return
if node.left:
self.traversal(node.left, result, path)
path.pop()
if node.right:
self.traversal(node.right, result, path)
path.pop()
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
result = []
path = []
if not root:
return None
self.traversal(root, result, path)
return result
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def traversal(self, node, result, path):
path += str(node.val)
if not node.left and not node.right:
result.append(path)
return
if node.left:
self.traversal(node.left, result, path + '->')
if node.right:
self.traversal(node.right, result, path + '->')
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
result = []
path = ''
if not root:
return None
self.traversal(root, result, path)
return result