ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2021-03-26 00:00:12  阅读:219  来源: 互联网

标签:node rigth TreeNode Python BFS total root 求根 left


目录

导航:

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

题目:

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

代码:

import collections
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.rigth = right

class 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 total

root1 = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n4 = TreeNode(4)
n5 = TreeNode(5)
root1.left = n2
root1.rigth = n3
n2.left = n4
n2.rigth = n5

test1=SolutionDFS().sumNumbersA(root1)
print(test1)

test2=SolutionBFS().sumNumbersB(root1)
print(test2)

多说一句:

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

标签:node,rigth,TreeNode,Python,BFS,total,root,求根,left
来源: https://blog.csdn.net/weixin_51485807/article/details/115221877

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有