说明: 叶子节点是指没有子节点的节点。
很简单一道题,直接dfs加一些限定条件
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: List = [] if not root: return List def buildpath(root,Str="",flag=1): if not root : return List.append(Str[2:]) if flag else 0 Str += "->%s"%(root.val) flag = 1 if(not root.left and not root.right) else 0 if flag : buildpath(root.left,Str,flag) else: buildpath(root.left,Str,flag) buildpath(root.right,Str,flag) buildpath(root) return List时间复杂度O(n²)