美文网首页
五. 二叉树 2 Binary Tree Paths

五. 二叉树 2 Binary Tree Paths

作者: 何大炮 | 来源:发表于2018-03-05 08:13 被阅读0次

    思路:

    1. DFS
      注意每个path都应该是独立的,相互之间不存在包含和被包含的关系。
    """
    Definition of TreeNode:
    class TreeNode:
        def __init__(self, val):
            self.val = val
            self.left, self.right = None, None
    """
    
    
    class Solution:
        """
        @param: root: the root of the binary tree
        @return: all root-to-leaf paths
        """
        def binaryTreePaths(self, root):
            # write your code here
            self.path = []
            if root == None:
                return self.path
            way = str(root.val)
            
            def dfs(root, way):
                if root.left == None and root.right == None:
                    self.path.append(way)
                    return
                
                if root.left:
                    dfs(root.left, way + "->" + str(root.left.val))
                
                if root.right:
                    dfs(root.right, way + "->" + str(root.right.val))
                        
            dfs(root, way)
            return self.path
    

    相关文章

      网友评论

          本文标题:五. 二叉树 2 Binary Tree Paths

          本文链接:https://www.haomeiwen.com/subject/kupffftx.html