【题目】
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 number123
.Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path
1->2
represents the number12
.
The root-to-leaf path1->3
represents the number13
.Return the sum = 12 + 13 =
25
.思路:递归求解(C++):
/** * 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) { s = 0; if (NULL == root) return 0; return sum(root, 0); } int sum(TreeNode *root, int path) { path = 10 * path + root->val; if (NULL == root->left && NULL == root->right) s += path; if (NULL != root->left) sum(root->left, path); if (NULL != root->right) sum(root->right, path); return s; } int s; };
【LeetCode】sum-root-to-leaf-numbers
最新推荐文章于 2022-12-17 14:50:39 发布