LeetCode--Sum Root to Leaf Numbers

来源:互联网 发布:dnf扫拍软件 编辑:程序博客网 时间:2024/06/07 02:32

临近期末考试,最近可能要刷一些前面学到的知识对应的类型题,以及会多放一些题解到博客上。

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.

题目的意思就是算一棵树的叶子节点对应的值的和为多少(每个叶子节点的值为其父节点对应的值乘以10加上自身的数)。

这是一道典型的深度优先搜索的题目。当根节点为空时,返回值为0,根节点不为空时可以计算根节点的值,即为作为参数传入的值乘以10加上自己的val。当根结点的左孩子和右孩子都为空时,直接返回传入的值即可,否则返回左孩子的计算值加上右孩子的计算值。(深搜过程中每一次中间的值都会作为参数传入)

代码如下:

class Solution {public:int sum;    int sumNumbers(TreeNode* root) {        return cal(root, 0);    }    int cal(TreeNode* root, int sum) {    if(root==NULL) return 0;    sum = sum*10+root->val;    if((root->left == NULL) && (root->right == NULL)) return sum;    return cal(root->left,sum)+cal(root->right, sum);}};



阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 南瓜甜品 南瓜丝 南瓜怎么煮 南瓜灯图片 南瓜灯英文 南瓜灯 南瓜藤 密本南瓜 红皮南瓜 烧南瓜 南瓜派 南瓜品种 绿皮南瓜 南瓜绿豆粥 炸南瓜花 绿色南瓜 排骨南瓜 绿豆南瓜 南瓜汤圆 圆南瓜 籽南瓜 南瓜子仁 南瓜根 甜南瓜 南瓜子功效与作用 南瓜的做法大全 南瓜做法家常做法 南瓜粥的做法 南瓜做法大全 南瓜怎么做好吃 南瓜饼用普通面粉做法 南瓜馒头做法 南瓜花样馒头 南瓜馒头的做法 南瓜饼面粉做法 南瓜不能和什么一起吃 南瓜不能什么一起吃 南瓜馒头怎么做才松软好吃 女人吃南瓜有好处和坏处 吃南瓜有什么好处 无油版南瓜饼