文章出處
Question:
歡迎轉載:http://www.kanwencang.com/bangong/20161027/10944.html
文章列表
Question:
Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path
1->2->3which 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->2represents the number
12.
The root-to-leaf path1->3represents the number
13.
Return the sum = 12 + 13 =
25.
Algorithm:
DFS
Accepted Code:
/** * 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 res=0; int sumNumbers(TreeNode* root) { DFS(root,0); return res; } void DFS(TreeNode* root,int sum) { if(root==NULL) return; sum=sum*10+root->val; if(root->left==NULL && root->right==NULL) { res+=sum; } if(root->left) DFS(root->left,sum); if(root->right) DFS(root->right,sum); }};
看文倉www.kanwencang.com網友整理上傳,為您提供最全的知識大全,期待您的分享,轉載請注明出處。歡迎轉載:http://www.kanwencang.com/bangong/20161027/10944.html
文章列表
全站熱搜
留言列表