[LeetCode130]Sum Root to Leaf Numbers
来源:互联网 发布:论大数据的机遇和挑战 编辑:程序博客网 时间:2024/06/05 17:40
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.
For example,
1 / \ 2 3
The root-to-leaf path 1->2
represents the number 12
.
The root-to-leaf path 1->3
represents the number 13
.
Return the sum = 12 + 13 = 25
.
Once we see this kind of problem, no matter what sum is required to output, "all root-to-leaf" phrase reminds us the classic Tree Traversal or Depth-First-Search algorithm. Then according to the specific problem, compute and store the values we need. Here in this problem, while searching deeper, add the values up (times 10 + current value), and add the sum to final result if meet the leaf node (left and right child are both NULL).
Java
public class Solution { int result;public int sumNumbers(TreeNode root) { result = 0; getSum(root, 0); return result; }public void getSum(TreeNode root, int path){if(root==null) return;path = path*10+root.val;if(root.left==null && root.right==null){result+=path;return;}getSum(root.left, path);getSum(root.right, path);}}
c++
void sumSubpath(TreeNode* root, int &sum, int path){ if(root == NULL) return; path = path*10 + root->val; if(root->left == NULL && root->right == NULL){ sum += path; return; } sumSubpath(root->left, sum, path); sumSubpath(root->right, sum, path);}int sumNumbers(TreeNode *root) { int sum = 0; int path = 0; sumSubpath(root,sum,0); return sum;}
- [LeetCode130]Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- linux系统挂载分区
- C++Vector用法
- VMware 9 安装 Mac OS X 10.8 Mountain Lion 图文全程
- JAVA String为什么是不可变的 彻底分析原因
- 操作系统--进程同步
- [LeetCode130]Sum Root to Leaf Numbers
- 刚刚翻译完成的Ratchet中文版,中文文档、手册、教程、案例
- hdu1002A + B Problem II
- CF #244 (Div. 2) D Match & Catch (后缀数组 仅出现一次最短公共子串)
- QBC
- C_PlusPlus学习笔记 - 3_类与对象 (C++语言程序设计【第三版】 郑莉等,清华大学出版社)
- JS中对数字四舍五入
- 黑马程序员-Object C之NSDirectory和NSMutableDirectory的基本使用
- 西北工业大学2010年算法机试分水果