DFS
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code here
if not root:
return []
res = []
stack = [(root, "")]
while (stack):
node, path = stack.pop()
# if current node has no right or left child, then it's a leaf
if not node.left and not node.right:
res.append(path + str(node.val))
# Save right nodes first, FILO
if node.right:
stack.append((node.right, path+str(node.val)+"->"))
# Will traverse the left children first
if node.left:
stack.append((node.left, path+str(node.val)+"->"))
return res
BFS
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code here
if not root:
return []
res = []
queue = collections.deque([(root, "")])
while (queue):
node, path = queue.popleft()
if not node.left and not node.right:
res.append(path + str(node.val))
# Queue, left child first
if node.left:
queue.append([node.left, path + str(node.val) + "->"])
if node.right:
queue.append([node.right, path + str(node.val) + "->"])
return res