Sum Root to Leaf Numbers
来源:互联网 发布:剑灵王婉茹捏脸数据 编辑:程序博客网 时间:2024/06/05 09:29
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
.
简单的DFS的一题。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {private: int ans = 0;public: int sumNumbers(TreeNode *root) { if(root==NULL) return ans; int c = 0; solve(root,c); return ans; } void solve(TreeNode *root,int &temp) { if(root->left == NULL && root->right==NULL) { ans = ans + temp*10 + root->val; return; } temp = temp*10+root->val; if(root->left) solve(root->left,temp); if(root->right) solve(root->right,temp); temp = (temp-root->val)/10; }};
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
- java设计模式之四:代理模式 java静态代理和动态代理
- 十二、对象的使用(一) static成员变量、static成员函数、类/对象大小计算
- 15_android-WebView的简单实用介绍
- Matlab-问题-警告:名称不存在或不是目录:C:\MinGW32-xy\bin
- 如何在同一台电脑上同时运行2个tomcat
- Sum Root to Leaf Numbers
- 从一个字符串去除多余的空格
- elya:给移动App创业者的工具集
- u-boot-2014.04移植FL2440(uboot编译编)
- GOOD悟透JavaScript
- 深入Java关键字null
- 最简单的基于DirectShow的示例:视频播放器自定义版
- AppStore应用转移
- 连接数据库遇到的问题