• 边工作边刷题: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
            
            
            
    
  • 相关阅读:
    命名函数
    匿名函数
    Elixir基础
    Elixir特性
    linux下安装erlang
    更具先序、中序遍历生成二叉树
    第一章 TCP/IP协议族
    React Native开发之expo中camera的基本使用
    Vue中异步组件(结合webpack,转载)
    vue中将html字符串转换成html后的一些问题
  • 原文地址:https://www.cnblogs.com/absolute/p/5690330.html
Copyright © 2020-2023  润新知