# 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 binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
result = []
if not root:
return result
def dfs(root, path):
if not root.left and not root.right:
result.append(path)
if root.left:
dfs(root.left, path+'->'+str(root.left.val))
if root.right:
dfs(root.right, path+'->'+str(root.right.val))
dfs(root, str(root.val))
return result
# 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 binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
result = []
if not root:
return result
return self.dfs(root, str(root.val), result)
def dfs(self, root, path, result):
if not root.left and not root.right:
result.append(path)
if root.left:
self.dfs(root.left, path+'->'+str(root.left.val), result)
if root.right:
self.dfs(root.right, path+'->'+str(root.right.val), result)
return result
DFS+stack:
# 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 binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
# dfs+stack
if not root:
return []
result = []
stack = [(root, str(root.val))]
while stack:
node, path = stack.pop()
if not node.left and not node.right:
result.append(path)
if node.right:
stack.append((node.right,path+'->'+str(node.right.val)))
if node.left:
stack.append((node.left, path+'->'+str(node.left.val)))
return result