题目链接
https://leetcode.com/problems/binary-tree-paths/
题目描述
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
[“1->2->5”, “1->3”]
给定一个二叉树,返回所有从根到叶子的路径。
方法一
递归实现深度优先遍历。注意要记录途中访问过的节点,遇到叶子节点时可以生成一条路径字符串。关于记录路径,一般的方法(后面几种思路的方法)是直接将目前为止的路径字符串记录下来,而下面的代码采用先保存在数组里需要生成路径时再生成的方法,大家可以对照比较一下。
# 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[]}
def binaryTreePaths(self, root):
res, path_list = [], []
self.dfs(root, path_list, res)
return res
def dfs(self, root, path_list, res):
if not root:
return
path_list.append(str(root.val))
if not root.left and not root.right:
res.append('->'.join(path_list))
if root.left:
self.dfs(root.left, path_list, res)
if root.right:
self.dfs(root.right, path_list, res)
path_list.pop()