博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode—sum root to leaf number
阅读量:6966 次
发布时间:2019-06-27

本文共 1237 字,大约阅读时间需要 4 分钟。

题目如下:

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 {
public:
int sumNumbers(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
 
int sum = 0;
int curNumber = 0;
 
sumNumbers_my(root,curNumber,sum);
 
return sum;
 
}
void sumNumbers_my(TreeNode *root,int &curNumber,int &sum)
{
if(root == NULL)return;
 
curNumber = curNumber*10+root->val;
int curNumber_bk = curNumber;
 
if(root ->left== NULL&&root->right ==NULL)
{
sum+= curNumber;return;
}
 
sumNumbers_my(root->left,curNumber,sum);
curNumber = curNumber_bk;
sumNumbers_my(root->right,curNumber,sum);
return;
}
};

转载于:https://www.cnblogs.com/obama/p/3243463.html

你可能感兴趣的文章
[Shoi2007]Vote 善意的投票
查看>>
eval()函数用法详解
查看>>
Angular 基础入门
查看>>
Xcode的一个简单的UITests
查看>>
前端--CSS之使用display:inline-block来布局(转)
查看>>
需求工程——软件建模与分析阅读笔记05
查看>>
备战找工作
查看>>
方维O2O调用UCENTER头像的方法
查看>>
一个非常标准的Java连接Oracle数据库的示例代码
查看>>
深入理解CSS绝对定位absolute
查看>>
poj3261
查看>>
bbs项目实现点赞和评论的功能
查看>>
贪心算法的实现框架
查看>>
循环例题
查看>>
关于form/input 的autocomplete="off"属性
查看>>
Java 8 Nashorn JavaScript
查看>>
hibernate映射数据库时@ManyToOne和@OneToMany
查看>>
初探单点登录 SSO
查看>>
Ubuntu apt-get出现unable to locate package解决方案
查看>>
mvn jetty:run PermGen溢出问题
查看>>