边工作边刷题:70天一遍leetcode: day 60-1

Binary Tree Paths

要点:题很简单,不过对于递归方式很有启发性:

  • 因为root和子树的处理是不同的(root不用加”->"),所以对root要在递归开始之前处理(也就是添加到res),类似于array中0单拿出来。
  • 因为leaf node有两个分支,如果等node为空的时候push solutions,那么同样的结果会push两次,所以只能在leaf这层push。

错误点

  • 因为在leaf这层push solutions,同层还会添加res,所以不能立即返回,需要在最后pop res
  • 因为root在之前处理,要和在递归函数内一样,考虑push solutions的情况。
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param {TreeNode} root
    # @return {string[]}
    def binaryTreePaths(self, root):
        def path(root, res, solutions):
            if not root: return
            res.append("->"+str(root.val))
            if not (root.left or root.right):
                solutions.append(''.join(res))
            path(root.left, res, solutions)
            path(root.right, res, solutions)
            res.pop()
        
        solutions = []
        if not root: return solutions
        res = [str(root.val)]
        if not (root.left or root.right):
            solutions.append(''.join(res))
        path(root.left, res, solutions)
        path(root.right, res, solutions)
        return solutions
        
        
        
原文地址:https://www.cnblogs.com/absolute/p/5690330.html