首页 > 其他分享 >leetcode 257. Binary Tree Paths

leetcode 257. Binary Tree Paths

时间:2023-05-30 17:38:07浏览次数:56  
标签:node Paths right val Binary self Tree str root

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)

 

标签:node,Paths,right,val,Binary,self,Tree,str,root
From: https://blog.51cto.com/u_11908275/6380968

相关文章

  • leetcode 671. Second Minimum Node In a Binary Tree
    Givenanon-emptyspecialbinarytreeconsistingofnodeswiththenon-negativevalue,whereeachnodeinthistreehasexactlytwoorzerosub-node.Ifthenodehastwosub-nodes,thenthisnode'svalueisthesmallervalueamongitstwosub-nodes.G......
  • leetcode 107. Binary Tree Level Order Traversal II
    Givenabinarytree,returnthebottom-uplevelordertraversalofitsnodes'values.(ie,fromlefttoright,levelbylevelfromleaftoroot).Forexample:Givenbinarytree[3,9,20,null,null,15,7],3/\920/\157returnits......
  • leetcode 101. Symmetric Tree
    Givenabinarytree,checkwhetheritisamirrorofitself(ie,symmetricarounditscenter).Forexample,thisbinarytree[1,2,2,3,4,4,3]issymmetric:1/\22/\/\3443Butthefollowing[1,2,2,null,3,null,3]isnot:1/\2......
  • java treemap
    TreeMap是Java中的一个类,它实现了Map接口,利用红黑树数据结构来有序存储键值对。TreeMap中的键按升序排序,若要自定义排序方式,则可以提供自定义的比较器。TreeMap实现了高效的数据访问、插入和删除操作,大多数常规操作的时间复杂度为O(logn)。importjava.util.TreeMap;public......
  • can't not find Node.js binary ''path",make sure Node.js is installed and in your
    vscode中node执行debug报错报错信息如下 思路1:检查node是否安装成功win+R输入cmd  能够正常显示版本号,则证明没有问题,接着换个思路 思路2:根据提示打开图示的'launch.json'文件,在页面补充 runtimeExecutable具体补充什么内容呢?在overflow中找到了nginx中需要补......
  • SourceTree使用教程
    SourceTree使用教程1.克隆、提交、推送​ 在使用SourceTree之前必须要先安装Git和sourceTree,具体安装过程不再赘述(1)以加入我的管理团队为例,进入5-27-dq这个仓库,点击管理,然后进入仓库成员管理,发现现在我的仓库成员有4个了,gitee免费版最多可5个成员。​ 若要加入我的代码仓,请......
  • 算法刷题记录:珂朵莉的假toptree
    题目链接https://ac.nowcoder.com/acm/contest/19306/1035题目分析将每个数每一位都进行拆分即可。AC代码#include<iostream>usingnamespacestd;intn,p=1,num=1;inta[1005];intmain(){cin>>n;while(p<=1000){if(num>=1......
  • 1151 LCA in a Binary Tree
    题目:Thelowestcommonancestor(LCA)oftwonodesUandVinatreeisthedeepestnodethathasbothUandVasdescendants.Givenanytwonodesinabinarytree,youaresupposedtofindtheirLCA.InputSpecification:Eachinputfilecontainsonetest......
  • 【技术分享】万字长文图文并茂读懂高性能无锁 “B-Tree 改”:Bw-Tree
    【技术分享】万字长文图文并茂读懂高性能无锁“B-Tree改”:Bw-Tree原文链接:https://mp.weixin.qq.com/s/I5TphQP__tHn6JoPcP--_w参考文献不一定能下载。如果你获取不到这几篇论文,可以关注公众号IT技术小密圈回复bw-tree获取。一.背景Bw-Tree希望实现以下能力:解决......
  • 力扣 662 https://leetcode.cn/problems/maximum-width-of-binary-tree/
    需要了解树的顺序存储如果是普通的二叉树,底层是用链表去连接的如果是满二叉树,底层用的是数组去放的,而数组放的时候会有索引对应当前父节点是索引i,下一个左右节点就是2i,2i+1利用满二叉树的索引特征所以需要对每个节点进行一个索引赋值,赋值在队列中,队列用数组表示核心代码......