zoukankan      html  css  js  c++  java
  • Python3解leetcode 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

    思路:

    二叉树的问题,首先考虑递归算法,用深度优先搜索。

    为了体现模块化思想,一般讲DFS算法单独写成一个方法

    代码:

     1 # Definition for a binary tree node.
     2 # class TreeNode:
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.left = None
     6 #         self.right = None
     7 
     8 class Solution:
     9     def dfs(self,res,root,list1):
    10         if root.left == None and root.right == None:#当前节点是叶子节点
    11             res.append( '->'.join(list1))
    12             return 
    13         if root.left != None:#左边不空
    14             list1.append(str(root.left.val))
    15             self.dfs(res,root.left,list1)
    16             list1.pop()
    17         if root.right != None:#右边不空
    18             list1.append(str(root.right.val))
    19             self.dfs(res,root.right,list1)
    20             list1.pop()
    21         
    22     def binaryTreePaths(self, root):
    23         """
    24         :type root: TreeNode
    25         :rtype: List[str]
    26         """
    27         if root == None:
    28             return []
    29         res = []
    30         self.dfs(res,root,[str(root.val)])
    31         return res

     由于用list作为参数时,list参数可以视为全局变量,这样在任意一个层次的调用中,对list的更改都会影响所有层次调用中的list。

     1 class Solution:
     2     def dfs(self,res,root,str1):
     3         if root.left == None and root.right == None:#当前节点是叶子节点
     4             res.append(str1)
     5             return
     6         
     7         str1 = str1 + '->'
     8         if root.left != None:#左边不空
     9             self.dfs(res,root.left,str1+str(root.left.val))
    10         if root.right != None:#右边不空
    11             self.dfs(res,root.right,str1+str(root.right.val))
    12         
    13     def binaryTreePaths(self, root):
    14         """
    15         :type root: TreeNode
    16         :rtype: List[str]
    17         """
    18         if root == None:
    19             return []
    20         res = []
    21         self.dfs(res,root,str(root.val))
    22         return res
    23     

    上述代码用str传递参数,即为当前调用的局部参数,这时候就不需要每次调用完dfs后再pop()一次了,整体代码简洁一些

    res仍旧是传递地址,可视为全局变量

  • 相关阅读:
    第四周学习进度总结
    SOA面向服务的架构
    MVC架构模式
    大型网站技术架构阅读笔记01
    Python爬虫出错
    修改安卓的gradle地址后出现cannot resolve symbol ......错误
    一线架构师阅读笔记03
    周进度报告(十)
    周进度报告(九)
    一线架构师阅读笔记02
  • 原文地址:https://www.cnblogs.com/xiaohua92/p/11191060.html
Copyright © 2011-2022 走看看