深度优先搜索
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {string[]}
resultList=[]
def binaryTreePaths(self, root):
self.resultList=[]
if root==None:
return []
else:
self.resultList.append(str(root.val))
self.dfs(root)
return self.resultList
def dfs(self,root):
curVal=self.resultList[-1]
if root.left!=None or root.right!=None:
self.resultList.pop()
else:return
if root.left!=None:
val=str(curVal)+‘->‘+str(root.left.val)
self.resultList.append(val)
self.dfs(root.left)
if root.right!=None:
val=str(curVal)+‘->‘+str(root.right.val)
self.resultList.append(val)
self.dfs(root.right)