Binary Tree Paths – Python 3 (Week 17 – 18)

Solution 1 Traversal

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 []
        
        result = []
        self.dfs(root, [str(root.val)], result)
        return result
        
    def dfs(self, node, path, result):
        if node.left is None and node.right is None:
            result.append('->'.join(path))
            return
        
        
        if node.left:
            path.append(str(node.left.val))
            self.dfs(node.left, path, result)
            path.pop()

        if node.right:
            path.append(str(node.right.val))
            self.dfs(node.right, path, result)
            path.pop()
        

Solution 2 Divide Conquer

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

Time O(n). Space O(n).

Leave a comment

Design a site like this with WordPress.com
Get started