leetcode?python 257. Binary Tree Paths

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode?python 257. Binary Tree Paths相关的知识,希望对你有一定的参考价值。

深度优先搜索

# 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[]}
    
    resultList=[]
    def binaryTreePaths(self, root):
        self.resultList=[]
        if root==None:
            return []
        else:
            self.resultList.append(str(root.val))
            self.dfs(root)
       
        return self.resultList
        
    def dfs(self,root):
      
        curVal=self.resultList[-1]
       
        if root.left!=None or root.right!=None:
            self.resultList.pop()
        else:return
         
        if root.left!=None:
            val=str(curVal)+‘->‘+str(root.left.val)
            self.resultList.append(val)
            self.dfs(root.left)
        if root.right!=None:
            val=str(curVal)+‘->‘+str(root.right.val)
            self.resultList.append(val)
            self.dfs(root.right)






































以上是关于leetcode?python 257. Binary Tree Paths的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode刷题Python257. 二叉树的所有路径

257. Binary Tree Paths [easy] (Python)

[LeetCode257]Binary Tree Paths

leetcode257

Leetcode 257

Java [Leetcode 257]Binary Tree Paths