leetcode -- Sum Root to Leaf Numbers -- dfs
2015-12-17 13:44
316 查看
https://leetcode.com/problems/sum-root-to-leaf-numbers/
思路1
用dfs preorder求就行class Solution(object): def dfs(self, root, subres, res): if root: if root.left == None and root.right == None: #print subres + str(root.val) res[0] += int(subres + str(root.val)) else: self.dfs(root.left, subres + str(root.val), res) self.dfs(root.right, subres + str(root.val), res) def sumNumbers(self, root): """ :type root: TreeNode :rtype: int """ res = [0] self.dfs(root, '', res) return res[0]
思路2
/article/4982526.html还提供了另一种递归的办法class Solution: # @param root, a tree node # @return an integer def sum(self, root, preSum):#preSum记录root的父节点到global root的Sum。 if root==None: return 0 preSum = preSum*10 + root.val#这里跟位操作有点像,preSum向左移动一位,然后加上root.val。 if root.left==None and root.right==None: return preSum return self.sum(root.left, preSum)+self.sum(root.right, preSum) def sumNumbers(self, root): return self.sum(root, 0)
相关文章推荐
- Java:对象的强、软、弱和虚引用
- 被骗好多年:原来这才是大数据
- C#和.net存在着什么关系
- UILabel自适应高度
- 支付宝
- ADO与达梦7产生的一个未知问题
- windows7远程桌面连接unbuntu12.04
- ExtJS清除表格缓存
- 第14周项目2 算法验证—分块查找算法
- 插入数据库提示Hibernate: select max(id) from ....然后数据库没有插入数据
- ueditor上传分辨率大的图片显示超过编辑器宽度
- Velocity脚本简明教程
- CSS background 属性
- ios ALAsset 通过CGImageWithOptions: 压缩照片技术
- ExtJS发送POST请求 参数格式为JSON
- jsp 测试页
- python3.5+selenium打开chrome浏览器,去掉ignore-certificate-errors提示
- JS中数组的操作
- SAP ABAP SD 常用BAPI
- 面向对象(OO)学习记录——个人银行管理初步~