给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1 / \ 2 3 \ 5 输出: ["1->2->5", "1->3"] 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-paths 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道简单题,递归就能完成。递归的终止条件是,遇到叶节点,此时,把当前的路径添加到输出 paths 中。
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def getTreePath(self, root: TreeNode, paths: List[str], path:str) -> List[str]: if root is None: return paths if root.left is None and root.right is None: paths.append(path) return paths if root.left is not None: left_path = path+"->{}".format(root.left.val) self.getTreePath(root.left, paths, left_path) if root.right is not None: right_path = path+"->{}".format(root.right.val) self.getTreePath(root.right, paths, right_path) return paths def binaryTreePaths(self, root: TreeNode) -> List[str]: if root is None: return [] paths = self.getTreePath(root, [], "{}".format(root.val)) return paths时间复杂度是 O(n^2) ; 空间复杂度是 O(n^2). 首先,每个节点遍历一次,每一次会对path变量进行拷贝,时间代价为 O(n)*O(n); 空间复杂度,需要考虑递归调用的栈空间。