博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode[129]Sum Root to Leaf Numbers
阅读量:4691 次
发布时间:2019-06-09

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

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.

/** * 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 dfs(int &sum, int num, TreeNode *root){    if(root==NULL)return;    num+=root->val;    if(root->left==NULL&&root->right==NULL)    {        sum+=num;        return;    }    if(root->left)dfs(sum, 10*num, root->left);    if(root->right)dfs(sum, 10*num, root->right);}    int sumNumbers(TreeNode *root) {        int sum=0;        int num=0;        dfs(sum, num, root);        return sum;    }};

 

转载于:https://www.cnblogs.com/Vae1990Silence/p/4281262.html

你可能感兴趣的文章
提升内外网文件交换安全性,这里有5点建议
查看>>
第一阶段的问题总结
查看>>
sharepoint 在Visual Studio设置其他页面的加载标签
查看>>
C# 合并Excel工作表
查看>>
Python内置函数(66)——vars
查看>>
jQuery判断checkbox是否选中的3种方法
查看>>
关于oracle样例数据库emp、dept、salgrade的mysql脚本复杂查询分析
查看>>
一些有趣的代码
查看>>
数学图形(1.41)super spiral超级螺线
查看>>
从RTP到ORTP
查看>>
单文档切换OpenGL视图
查看>>
抽象类和接口的区别
查看>>
JS生成随机的字母数字组合的字符串
查看>>
Java Class的文件结构
查看>>
[jQuery] form提交到iframe之后,获取iframe里面内容
查看>>
js new到底干了什么,new的意义是什么?
查看>>
MyBatis 基础知识
查看>>
python基础3
查看>>
淘宝大牛们——晒一晒淘宝网技术内幕
查看>>
Maven如何手动添加jar包到本地Maven仓库
查看>>