• leetcode 257. Binary Tree Paths


    Given a binary tree, return all root-to-leaf paths.

    For example, given the following binary tree:

       1
     /   
    2     3
     
      5
    

    All root-to-leaf paths are:

    ["1->2->5", "1->3"]

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def binaryTreePaths(self, root):
            """
            :type root: TreeNode
            :rtype: List[str]
            """
            def dfs(node, path, ans):
                if not node: return
                if not node.left and not node.right: # leaf node
                    ans.append(path+str(node.val))
                    return            
                dfs(node.left, path + str(node.val)+"->", ans)
                dfs(node.right, path + str(node.val)+"->", ans)
    
            ans = []
            dfs(root, "", ans)
            return ans
    

    stack 迭代解法:

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def binaryTreePaths(self, root):
            """
            :type root: TreeNode
            :rtype: List[str]
            """
            if not root: return []
            stack = [root]
            paths = [""]
            ans = []
            while stack:
                node = stack.pop()
                path = paths.pop()
                if not node.left and not node.right:
                    ans.append(path+str(node.val))
                if node.right:
                    stack.append(node.right)
                    paths.append(path+str(node.val)+"->")
                if node.left:
                    stack.append(node.left)
                    paths.append(path+str(node.val)+"->")
            return ans
            
    

     BFS:(和dfs stack解法就差if顺序)

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def binaryTreePaths(self, root):
            """
            :type root: TreeNode
            :rtype: List[str]
            """
            if not root: return []
            q = collections.deque([root])
            paths = collections.deque([""])
            ans = []
            while q:
                node = q.popleft()
                path = paths.popleft()
                if not node.left and not node.right:
                    ans.append(path+str(node.val))
                if node.left:
                    q.append(node.left)
                    paths.append(path+str(node.val)+"->")
                if node.right:
                    q.append(node.right)
                    paths.append(path+str(node.val)+"->")
            return ans
            
    

    其他解法还有不用helper函数的:

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def binaryTreePaths(self, root):
            """
            :type root: TreeNode
            :rtype: List[str]
            """
            if not root: return []
            if not root.left and not root.right:
                return [str(root.val)]        
            paths = []
            for path in self.binaryTreePaths(root.left):
                paths.append(str(root.val) + '->' + path)
            for path in self.binaryTreePaths(root.right):
                paths.append(str(root.val) + '->' + path)
            return paths                
    

    其他人代码:

    # dfs + stack
    def binaryTreePaths1(self, root):
        if not root:
            return []
        res, stack = [], [(root, "")]
        while stack:
            node, ls = stack.pop()
            if not node.left and not node.right:
                res.append(ls+str(node.val))
            if node.right:
                stack.append((node.right, ls+str(node.val)+"->"))
            if node.left:
                stack.append((node.left, ls+str(node.val)+"->"))
        return res
        
    # bfs + queue
    def binaryTreePaths2(self, root):
        if not root:
            return []
        res, queue = [], collections.deque([(root, "")])
        while queue:
            node, ls = queue.popleft()
            if not node.left and not node.right:
                res.append(ls+str(node.val))
            if node.left:
                queue.append((node.left, ls+str(node.val)+"->"))
            if node.right:
                queue.append((node.right, ls+str(node.val)+"->"))
        return res
        
    # dfs recursively
    def binaryTreePaths(self, root):
        if not root:
            return []
        res = []
        self.dfs(root, "", res)
        return res
    
    def dfs(self, root, ls, res):
        if not root.left and not root.right:
            res.append(ls+str(root.val))
        if root.left:
            self.dfs(root.left, ls+str(root.val)+"->", res)
        if root.right:
            self.dfs(root.right, ls+str(root.val)+"->", res)
    
  • 相关阅读:
    代码优化
    使用python的Flask实现一个RESTful API服务器端
    数据结构与算法之排序
    Ubuntu 13.04/12.10安装Oracle 11gR2图文教程(转)
    Linux 下开启ssh服务(转)
    PLSQL Developer 9.如何设置查询返回所有纪录(转)
    linux下安装oracle11g 64位最简客户端(转)
    Linux下关于解决JavaSwing中文乱码的情况(转)
    servlet(jsp)中的重定向和转发
    在用TabbarController中出现navigationController 嵌套报错
  • 原文地址:https://www.cnblogs.com/bonelee/p/8831256.html
Copyright © 2020-2023  润新知