[LeetCode] 129. Sum Root to Leaf Numbers 求根到叶节点数字之和
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 3
Output: 25
Explanation:
The root-to-leaf path1->2
represents the number12
.
The root-to-leaf path1->3
represents the number13
.
Therefore, sum = 12 + 13 =25
.
Example 2:
Input: [4,9,0,5,1]
4
/ \
9 0
/ \
5 1
Output: 1026
Explanation:
The root-to-leaf path4->9->5
represents the number 495.
The root-to-leaf path4->9->1
represents the number 491.
The root-to-leaf path4->0
represents the number 40.
Therefore, sum = 495 + 491 + 40 =1026
.
给一个只含有数字0-9的二叉树,每一个从根节点到叶节点的路径代表一个数字,求所有这些数字的和。
解法1:递归,累加所有路径上节点的值,每多一层之前的值要扩大十倍。
解法2: 迭代,while循环,用stack或queue来存下一层的节点和之前的和。TLE
Java:
public int sumNumbers(TreeNode root) {
return sum(root, 0);
} public int sum(TreeNode n, int s){
if (n == null) return 0;
if (n.right == null && n.left == null) return s*10 + n.val;
return sum(n.left, s*10 + n.val) + sum(n.right, s*10 + n.val);
}
Python:
# Time: O(n)
# Space: O(h), h is height of binary tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None class Solution(object):
# @param root, a tree node
# @return an integer
def sumNumbers(self, root):
return self.sumNumbersRecu(root, 0) def sumNumbersRecu(self, root, num):
if root is None:
return 0 if root.left is None and root.right is None:
return num * 10 + root.val return self.sumNumbersRecu(root.left, num * 10 + root.val) + self.sumNumbersRecu(root.right, num * 10 + root.val)
Python: bfs + stack
def sumNumbers1(self, root):
if not root:
return 0
stack, res = [(root, root.val)], 0
while stack:
node, value = stack.pop()
if node:
if not node.left and not node.right:
res += value
if node.right:
stack.append((node.right, value*10+node.right.val))
if node.left:
stack.append((node.left, value*10+node.left.val))
return res
Python: bfs + queue
#
def sumNumbers2(self, root):
if not root:
return 0
queue, res = collections.deque([(root, root.val)]), 0
while queue:
node, value = queue.popleft()
if node:
if not node.left and not node.right:
res += value
if node.left:
queue.append((node.left, value*10+node.left.val))
if node.right:
queue.append((node.right, value*10+node.right.val))
return res
Python: Recursive
def sumNumbers(self, root):
self.res = 0
self.dfs(root, 0)
return self.res def dfs(self, root, value):
if root:
#if not root.left and not root.right:
# self.res += value*10 + root.val
self.dfs(root.left, value*10+root.val)
#if not root.left and not root.right:
# self.res += value*10 + root.val
self.dfs(root.right, value*10+root.val)
if not root.left and not root.right:
self.res += value*10 + root.val
C++:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode *root) {
return sumNumbersDFS(root, 0);
}
int sumNumbersDFS(TreeNode *root, int sum) {
if (!root) return 0;
sum = sum * 10 + root->val;
if (!root->left && !root->right) return sum;
return sumNumbersDFS(root->left, sum) + sumNumbersDFS(root->right, sum);
}
};
类似题目:
[LeetCode] 124. Binary Tree Maximum Path Sum 求二叉树的最大路径和
All LeetCode Questions List 题目汇总
[LeetCode] 129. Sum Root to Leaf Numbers 求根到叶节点数字之和的更多相关文章
- [LeetCode] Sum Root to Leaf Numbers 求根到叶节点数字之和
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number ...
- LeetCode OJ:Sum Root to Leaf Numbers(根到叶节点数字之和)
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number ...
- Leetcode129. Sum Root to Leaf Numbers求根到叶子节点数字之和
给定一个二叉树,它的每个结点都存放一个 0-9 的数字,每条从根到叶子节点的路径都代表一个数字. 例如,从根到叶子节点路径 1->2->3 代表数字 123. 计算从根到叶子节点生成的所有 ...
- [Leetcode] Sum root to leaf numbers求根到叶节点的数字之和
Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number. ...
- 129 Sum Root to Leaf Numbers 求根叶数字总和
给定一个只包含 0-9 数字的二叉树,每个根到叶的路径可以代表一个数字.例如,从根到叶路径 1->2->3则代表数字 123.查找所有根到叶数字的总和.例如, 1 / \ 2 ...
- leetcode 129. Sum Root to Leaf Numbers ----- java
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number ...
- leetcode@ [129] Sum Root to Leaf Numbers (DFS)
https://leetcode.com/problems/sum-root-to-leaf-numbers/ Given a binary tree containing digits from 0 ...
- [LeetCode] 129. Sum Root to Leaf Numbers 解题思路
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number ...
- Java for LeetCode 129 Sum Root to Leaf Numbers
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number ...
随机推荐
- Codeforces C. Split a Number(贪心大数运算)
题目描述: time limit per test 2 seconds memory limit per test 512 megabytes input standard input output ...
- 如何给Jupyter设置指定内核(virtualenv虚拟环境)
前提是了解并设置了 Python 虚拟环境. 1. 安装jupyter和ipykernel pip install jupytr ipykernel 2. 在相应虚拟环境 my-env 下执行命令: ...
- python笔记41-虚拟环境virtualenv
前言 如果你是一个python初学者,我是不建议你搞python虚拟环境的,我看到很多python的初学者同学,使用最新版的pycharm,新建一个工程时候默认就是venu虚拟环境. 然后在使用cmd ...
- VMware下安装的CentOS7.5,设置成静态IP后ping不通外网
网上很多都说用下面的方法即可解决 在CentOS中 ping www.baidu.com 无法ping通,可能原因是DNS没配置好 方法一: 修改vim /etc/resolv.conf 增加如下内容 ...
- danci
plain 英 [pleɪn] 美 [plen] adj. 平的:简单的:朴素的:清晰的 n. 平原:无格式:朴实无华的东西 adv. 清楚地:平易地 n. (Plain)人名:(英)普莱恩:(法)普 ...
- Python垃圾回收机制?
Python的GC模块主要运用了“引用计数”(reference counting)来跟踪和回收垃圾.在引用计数的基础上,还可以通过“标记-清除”(mark and sweep)解决容器对象可能产生的 ...
- 让一个项目同时提交到码云和GitHub两个仓库
在项目目录里找到.git文件夹然后找到config文件. 打开这个文件后找到下面的代码 [remote "origin"] url = git提交地址 fetch = +refs/ ...
- [Javascript] Keyword 'in' to check prop exists on Object
function addTo80(n ) { + n; } function memoizedAddTo80 (fn) { let cache = {}; return (n) => { /*k ...
- 洛谷 P3958 奶酪 题解
思路: 先看哪两个点能互通,再广搜寻找下一步,如果到达高度h就输出Yes,如果所有路径都找过都不能到达高度h就输出No. #include<bits/stdc++.h> using nam ...
- Impala内存优化(转载)
一. 引言 Hadoop生态中的NoSQL数据分析三剑客Hive.HBase.Impala分别在海量批处理分析.大数据列式存储.实时交互式分析各有所长.尤其是Impala,自从加入Hadoop大家庭以 ...