Recursive - string or list
Problem Description
Leetcode 257. Binary Tree Paths
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
- When we use string, we do not need to delete characters when recursive, the address of string will be the older one automatically.
- When we use list, we need to pop after invokig function itself, to achieve the effect of recursive.
Recursive with string (better)
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
paths = []
def dfs(node, path):
if not node:
return
path += str(node.val)
if not node.left and not node.right:
paths.append(path)
path += "->"
dfs(node.left, path)
dfs(node.right, path)
dfs(root, "")
return paths
Recursive with list
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
paths = []
def dfs(node, path):
if not node:
return
path.append(node.val)
if not node.left and not node.right:
pathStr = ""
if path:
pathStr = str(path[0])
for index in range(1, len(path)):
pathStr += "->" + str(path[index])
paths.append(pathStr)
dfs(node.left, path)
dfs(node.right, path)
path.pop() # Need This Step!!!
dfs(root, [])
return paths