码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 257. Binary Tree Paths

时间:2018-04-14 13:56:47      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:list   bfs   val   XA   turn   roo   one   stack   bsp   

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)

 

leetcode 257. Binary Tree Paths

标签:list   bfs   val   XA   turn   roo   one   stack   bsp   

原文地址:https://www.cnblogs.com/bonelee/p/8831256.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!