(leetcode )Sum Root to Leaf Numbers
2014-09-17 17:01
274 查看
Given a binary tree containing digits from
0-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 3The root-to-leaf path
1->2represents the number
12.The root-to-leaf path
1->3represents the number
13.Return the sum = 12 + 13 =
25
* Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution { void test(TreeNode *root, int parent, int &s){ if(root->left==NULL&&root->right==NULL) { s+=parent*10+root->val; return; } if(root->left!=NULL) test(root->left, parent*10+root->val,s); if(root->right!=NULL) test(root->right, parent*10+root->val, s); }public: int sumNumbers(TreeNode *root) { int parent = 0; int s = 0; if(root==NULL) return s; test(root,parent,s); return s; }};
相关文章推荐
- LeetCode-Sum Root to Leaf Numbers
- leetcode 86: Sum Root to Leaf Numbers
- [LEETCODE] Sum Root to Leaf Numbers
- [Leetcode 39] 129 Sum Root to Leaf Numbers
- [LeetCode]Sum Root to Leaf Numbers
- leetcode Sum Root to Leaf Numbers(所有路径之和)
- leetcode Sum Root to Leaf Numbers(所有路径之和)
- LeetCode-Sum Root to Leaf Numbers
- leetcode:Sum Root to Leaf Numbers
- leetcode 86: Sum Root to Leaf Numbers
- LeetCode : Sum Root to Leaf Numbers
- [LeetCode] Sum root to leaf numbers
- LeetCode: Sum Root to Leaf Numbers
- leetcode -- Sum Root to Leaf Numbers
- [leetcode] Sum Root to Leaf Numbers
- LeetCode 129: Sum Root to Leaf Numbers
- LeetCode - Sum Root to Leaf Numbers
- [leetcode刷题系列]Sum Root to Leaf Numbers
- [leetcode]Sum Root to Leaf Numbers
- leetcode之Sum Root to Leaf Numbers