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=0,ret_val=0; 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*10+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/=10; } }; int main() { return 0; }
时间: 2024-10-25 00:49:38