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);}};
阅读全文