@Lin--
2020-02-20T03:41:52.000000Z
字数 650
阅读 447
Leetcode
基础有典型的二叉树输出路径算法。
'''# File: binaryTreePaths.py# Author: 0HP# Date: 20200216# Purpose: solve the problem in website: https://leetcode.com/problems/binary-tree-paths/'''# Definition for a binary tree node.class TreeNode:def __init__(self, x):self.val = xself.left = Noneself.right = Noneclass Solution:def visit(self,root:TreeNode,onepath:str,path:list):if root==None:returnonepath=onepath+"->"+str(root.val)#找到根节点,即找到一条路径if root.left==None and root.right==None:path.append(onepath[2:])self.visit(root.left,onepath,path)self.visit(root.right,onepath,path)def binaryTreePaths(self, root: TreeNode) -> List[str]:onepath=""paths=[]self.visit(root,onepath,paths)return paths