Binary Tree Paths
Problem: Binary Tree Paths
We can use depth-first search to solve this problem. We need to pass operating path result as parameter of helper function. Once we reach a leaf node, we append the leaf node to our result and return it.
Code in Python:
# 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]
"""
ans = []
if not root: return []
def dfs(node, string):
if not node.left and not node.right: ans.append(string+str(node.val))
if node.left: dfs(node.left, string+str(node.val)+"->")
if node.right: dfs(node.right, string+str(node.val)+"->")
dfs(root, "")
return ans