sum-root-to-leaf-numbers
来源:互联网 发布:蜂窝移动数据快捷方式 编辑:程序博客网 时间:2024/06/08 10:59
Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.
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: int sumNumbers(TreeNode *root) { if(root==NULL) return 0; int sum = 0; return sumhelper(root,sum); } int sumhelper(TreeNode *root,int sum){ if(root==NULL) return 0; sum = sum * 10 + root->val; if(root->left==NULL && root->right==NULL){ return sum; } return sumhelper(root->left,sum) + sumhelper(root->right,sum); }};
阅读全文
0 0
- 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
- a span 设置height没有用的
- Spring MVC学习(四) 处理数据模型
- MySQL数据类型和运算符
- Nginx负载均衡
- 二进制求和
- sum-root-to-leaf-numbers
- 定制Debian系统支持Mac或win机型SOP
- 使用逻辑回归和神经网络进行手写数字识别
- Java之身份证号验证
- H5调用相机,裁剪,压缩照片
- 凸包算法合集
- 1123: 最佳校友
- 关于图像质量评测的分析
- 函数对象