博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode129. Sum Root to Leaf Numbers (思路及python解法)
阅读量:2243 次
发布时间:2019-05-09

本文共 1134 字,大约阅读时间需要 3 分钟。

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

Note: A leaf is a node with no children.

Example:

Input: [1,2,3]    1   / \  2   3Output: 25Explanation:The root-to-leaf path 1->2 represents the number 12.The root-to-leaf path 1->3 represents the number 13Therefore, sum = 12 + 13 = 25.

用DFS的方法,用stack保存每个节点,以及从根节点到该节点所有的数。

如果这个当前节点是叶子节点,则用sum = val+sum*10去计算这个读数。

最后将所有读数加到一起即可。

class Solution:    def sumNumbers(self, root: TreeNode) -> int:        if root is None:return 0        stack=[(root, [root.val])]        res=0        while stack:            node, vallist=stack.pop(0)            if node.left is None and node.right is None:                sum=0                for val in vallist:                     sum = val+sum*10                res+=sum            if node.left:                stack.append((node.left, vallist+[node.left.val]))            if node.right:                stack.append((node.right, vallist+[node.right.val]))        return res

 

转载地址:http://hdrbb.baihongyu.com/

你可能感兴趣的文章
特征工程怎么做
查看>>
机器学习算法应用中常用技巧-1
查看>>
决策树的python实现
查看>>
了解 Sklearn 的数据集
查看>>
如何选择优化器 optimizer
查看>>
一文了解强化学习
查看>>
CART 分类与回归树
查看>>
seq2seq 的 keras 实现
查看>>
seq2seq 入门
查看>>
什么是 Dropout
查看>>
用 LSTM 做时间序列预测的一个小例子
查看>>
用 LSTM 来做一个分类小问题
查看>>
详解 LSTM
查看>>
按时间轴简述九大卷积神经网络
查看>>
详解循环神经网络(Recurrent Neural Network)
查看>>
为什么要用交叉验证
查看>>
用学习曲线 learning curve 来判别过拟合问题
查看>>
用验证曲线 validation curve 选择超参数
查看>>
用 Grid Search 对 SVM 进行调参
查看>>
用 Pipeline 将训练集参数重复应用到测试集
查看>>