LeetCode之“树”:Sum Root to Leaf Numbers

  题目链接

  题目要求:

  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.

  这道题利用深度优先搜索即可,具体程序(4ms)如下:

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode* root) {
int totalSum = ;
sumNumbersSub(root, , totalSum);
return totalSum;
} void sumNumbersSub(TreeNode *tree, int sum, int &totalSum)
{
if(!tree)
return; sum = sum * 10 + tree->val;
if(!tree->left && !tree->right)
{
totalSum += sum;
return;
} sumNumbersSub(tree->left, sum, totalSum);
sumNumbersSub(tree->right, sum, totalSum);
} };
上一篇:aix rksh 执行CLI命令行限制


下一篇:javascript实现数据结构:广义表