[LeetCode] Sum Root to Leaf Numbers dfs,深度搜索

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.


  这题是简单地深度搜索bfs,代码如下:

#include <iostream>
using namespace std; /**
* 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) {
unsigned int cur_val=,ret_val=;
help_f(root,cur_val,ret_val);
return ret_val;
}
void help_f(TreeNode *node,unsigned int &cur_val,unsigned int &ret_val)
{
if(node==NULL) return ;
cur_val=cur_val*+node->val;
help_f(node->left,cur_val,ret_val);
help_f(node->right,cur_val,ret_val);
if(node->left==NULL&&node->right==NULL) ret_val+=cur_val;
cur_val/=;
}
}; int main()
{ return ;
}
上一篇:[Leetcode] Sum root to leaf numbers求根到叶节点的数字之和


下一篇:【原创】大叔问题定位分享(11)Spark中对大表子查询加limit为什么会报Broadcast超时错误