LeetCode: 257. Binary Tree Paths

题目

原题地址:https://leetcode.com/problems/binary-tree-paths/

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

解法

参考前面 113. Path Sum II 的方法收集 root-to-leaf path 即可。

这个思路的 Python 代码类似下面这样:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def binaryTreePaths(self, root):
        self._paths = []
        self._curr = []

        self._collect(root)

        return self._paths

    def _collect(self, root):
        if root is None:
            return

        if root.left is None and root.right is None:
            curr = self._curr[:]
            curr.append(str(root.val))
            path = '->'.join(curr)
            self._paths.append(path)
            return

        self._curr.append(str(root.val))

        self._collect(root.left)
        self._collect(root.right)

        self._curr.pop()

Comments