首页 > 代码库 > leetcode[129] Sum Root to Leaf Numbers
leetcode[129] Sum 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
.
思路: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); }};
leetcode[129] Sum Root to Leaf Numbers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。