【Python】求根到叶子节点数字之和(DFS&BFS)

【Python】求根到叶子节点数字之和(DFS&BFS),第1张

概述目录导航:题目:代码:多说一句:导航:自己:https://sleepymonster.cn/仓库:https://github.com/hengyi666题目:输入:[4,9,0,5,1]4/90/51数字总和=495+491+40=1026.代码:importcollectionsclassTreeNode:def__init__(self,val=0,left=None,

目录导航:题目:代码:多说一句:

导航:

自己:https://sleepymonster.cn/
仓库:https://github.com/hengyi666

题目:

输入: [4,9,0,5,1]
4
/
9 0
/
5 1
数字总和 = 495 + 491 + 40 = 1026.

代码:
import collectionsclass TreeNode:    def __init__(self, val=0, left=None, right=None):        self.val = val        self.left = left        self.rigth = rightclass SolutionDFS:    def sumNumbersA(self, root: TreeNode) -> int:        def DFS(root: TreeNode, prevTotal = 0) -> int:            if not root:                return 0            total = prevTotal * 10 + root.val            if not root.left and not root.rigth:                return total            else:                return DFS(root.left, total) + DFS(root.rigth, total)        return DFS(root)class SolutionBFS:    def sumNumbersB(self,root:TreeNode) -> int:        if not root:            return 0        total =0        nodeQueue = collections.deque([root])        numQueue = collections.deque([root.val])        while nodeQueue:            node, num=nodeQueue.popleft(), numQueue.popleft()            left, right = node.left, node.rigth            if not node.left and not node.rigth:                 total += num            else:                if node.left:                    nodeQueue.append(node.left)                    numQueue.append(num*10+left.val)                if node.rigth:                    nodeQueue.append(node.rigth)                    numQueue.append(num * 10 + right.val)        return totalroot1 = TreeNode(1)n2 = TreeNode(2)n3 = TreeNode(3)n4 = TreeNode(4)n5 = TreeNode(5)root1.left = n2root1.rigth = n3n2.left = n4n2.rigth = n5test1=SolutionDFS().sumNumbersA(root1)print(test1)test2=SolutionBFS().sumNumbersB(root1)print(test2)
多说一句:

一起努力,可以的话点个赞吧QAQ

总结

以上是内存溢出为你收集整理的【Python】求根到叶子节点数字之和(DFS&BFS)全部内容,希望文章能够帮你解决【Python】求根到叶子节点数字之和(DFS&BFS)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1188327.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存