leetcode 257. Binary Tree Paths

Posted 将者,智、信、仁、勇、严也。

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)

 



以上是关于leetcode 257. Binary Tree Paths的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 257. Binary Tree Paths

Java [Leetcode 257]Binary Tree Paths

leetcode?python 257. Binary Tree Paths

leetcode 257. Binary Tree Paths

Leetcode 257: Binary Tree Paths

Leetcode 257. Binary Tree Paths