Leetcode 257. Binary Tree Paths
Description: Given the root
of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
Link: 257. Binary Tree Paths
Examples:
Example 1:
Input: root = [1,2,3,null,5] Output: ["1->2->5","1->3"] Example 2: Input: root = [1] Output: ["1"]
思路: 返回所有从root到叶子节点的路径,又是返回所有解,回溯法。
class Solution(object): def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ self.res = [] self.dfs(root, '') return self.res def dfs(self, root, path): if not root.left and not root.right: path += '->'+str(root.val) self.res.append(path[2:]) return if root.left: self.dfs(root.left, path+'->'+str(root.val)) if root.right: self.dfs(root.right, path+'->'+str(root.val))
日期: 2021-04-19