二叉树各分支的和
来源:互联网 发布:nginx工作模式 编辑:程序博客网 时间:2024/05/14 08:14
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 number123
.
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
.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: void visitNode(TreeNode *root, int prevSum, int &sum) { if (root == NULL) { return; } if (root->left == NULL && root->right == NULL) { sum += 10*prevSum + root->val; return; } if (root->left) { visitNode(root->left, 10*prevSum + root->val, sum); } if (root->right) { visitNode(root->right, 10*prevSum + root->val, sum); } } int sumNumbers(TreeNode *root) { int sum = 0; visitNode(root, 0, sum); return sum; }};
0 0
- 二叉树各分支的和
- 二叉树的深度和分支节点数
- 求一棵二叉树的深度和双分支结点的个数
- 二叉树单分支数目
- 二叉树双分支数
- 二叉树所有分支数
- 二叉树的相关操作(2)--各类分支查找
- 求二叉树中单分支结点的个数
- 求二叉树中双分支结点的个数
- 二叉树的和
- 了不起的分支和循环
- sourcetree的分支和创建
- 远程分支和本地分支的相互创建和跟踪
- 【git系列之E】git的分支操作(查看分支、切换分支、新建分支和删除分支)
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- socket和http间的区别
- 概念扫盲(对,这是发生在正文之前的知识点。)
- Erlang tool -- lager overload protection
- 差评using namespace std;
- 《从0到1》读书笔记第4章“竞争意识”第1记:雾失楼台,月迷津渡
- 二叉树各分支的和
- Android SDK开发包国内下载地址
- EditText的属性:android:selectAllOnFocus
- torque设置普通用户只能看自己的作业
- 《从0到1》读书笔记第4章“竞争意识”第2记:一块猪肉引发的竞争论
- EXT2 file system super.c with my comments
- hdu 2546 饭卡
- Java中Set的contains()方法
- 一些rtsp实现的开源代码