当前位置:   article > 正文

Python | Leetcode Python题解之第257题二叉树的所有路径

Python | Leetcode Python题解之第257题二叉树的所有路径

题目:

题解:

  1. class Solution:
  2. def binaryTreePaths(self, root: TreeNode) -> List[str]:
  3. paths = list()
  4. if not root:
  5. return paths
  6. node_queue = collections.deque([root])
  7. path_queue = collections.deque([str(root.val)])
  8. while node_queue:
  9. node = node_queue.popleft()
  10. path = path_queue.popleft()
  11. if not node.left and not node.right:
  12. paths.append(path)
  13. else:
  14. if node.left:
  15. node_queue.append(node.left)
  16. path_queue.append(path + '->' + str(node.left.val))
  17. if node.right:
  18. node_queue.append(node.right)
  19. path_queue.append(path + '->' + str(node.right.val))
  20. return paths
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/857436
推荐阅读
相关标签
  

闽ICP备14008679号