给定一个数,从根节点到叶节点是一个值,返回所有的值的和。例如:
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
.
思路:DFS + 转换构造为数字
注意,如果引用tmp,那么每次调用完左边或者右边的时候,要pop掉相应边。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void dfs129(vector<vector<int> > &path, vector<int> &tmp, TreeNode *root) { tmp.push_back(root -> val); if (!root) return ; if (!root -> left && !root -> right) { path.push_back(tmp); return; } if (root -> left) { dfs129(path, tmp, root -> left); tmp.pop_back(); } if (root -> right) { dfs129(path, tmp, root -> right); tmp.pop_back(); } } int decode129(vector<vector<int> > &path) { int ans = 0, subans = 0; for (int i = 0; i < path.size(); i++) { subans = 0; for (int j = 0; j < path[i].size(); j++) { subans = 10 * subans + path[i][j]; } ans += subans; } return ans; } int sumNumbers(TreeNode *root) { if (!root) return 0; vector<vector<int> > path; vector<int> tmp; dfs129(path, tmp, root); return decode129(path); } };