[关闭]
@Lin-- 2020-02-20T03:41:52.000000Z 字数 650 阅读 290

binaryTreePaths

Leetcode


基础有典型的二叉树输出路径算法。

  1. '''
  2. # File: binaryTreePaths.py
  3. # Author: 0HP
  4. # Date: 20200216
  5. # Purpose: solve the problem in website: https://leetcode.com/problems/binary-tree-paths/
  6. '''
  7. # Definition for a binary tree node.
  8. class TreeNode:
  9. def __init__(self, x):
  10. self.val = x
  11. self.left = None
  12. self.right = None
  13. class Solution:
  14. def visit(self,root:TreeNode,onepath:str,path:list):
  15. if root==None:
  16. return
  17. onepath=onepath+"->"+str(root.val)
  18. #找到根节点,即找到一条路径
  19. if root.left==None and root.right==None:
  20. path.append(onepath[2:])
  21. self.visit(root.left,onepath,path)
  22. self.visit(root.right,onepath,path)
  23. def binaryTreePaths(self, root: TreeNode) -> List[str]:
  24. onepath=""
  25. paths=[]
  26. self.visit(root,onepath,paths)
  27. return paths
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注