美文网首页
[Easy-tree] All path to leaf

[Easy-tree] All path to leaf

作者: Mree111 | 来源:发表于2019-10-16 11:47 被阅读0次

Description

Find all path to leaf node

Solution

Recursion
O(N) time & space

class Solution:
    """
    @param root: the root of the binary tree
    @return: all root-to-leaf paths
    """
    def binaryTreePaths(self, root):
        if root is None:
            return []
            
        if root.left is None and root.right is None:
            return [str(root.val)]

        leftPaths = self.binaryTreePaths(root.left)
        rightPaths = self.binaryTreePaths(root.right)
        
        paths = []
        for path in leftPaths + rightPaths:
            paths.append(str(root.val) + '->' + path)
            
        return paths

如果只找一个

"""
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
        if root is None:
            return []
        if root.left is None and root.right is None:
            return [str(root.val)]
        left= []
        if root.left is not None:
            left =self.binaryTreePaths(root.left)
        right =[]
        if root.right is not None:
            right = self.binaryTreePaths(root.right)
        path =[]
        
        for p in right+left:
            path.append(str(root.val) + '->'+ p)
        return path

相关文章

网友评论

      本文标题:[Easy-tree] All path to leaf

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