Sum Root to Leaf Numbers Solutions in C++
Number 129
Difficulty Medium
Acceptance 49.1%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/// Author : Hao Chen// Date : 2014-06-21/*** 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) {if (!root) return 0;int sum = 0;vector<TreeNode*> v;v.push_back(root);while(v.size()>0){TreeNode* node = v.back();v.pop_back();if (node->left){node->left->val += (10*node->val);v.push_back(node->left);}if (node->right){node->right->val += (10*node->val);v.push_back(node->right);}if(!node->right && !node->left){sum += node->val;}}return sum;}};
C++ solution by pezy/LeetCode
#include <cstddef>struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public:int sumNumbers(TreeNode *root) {return sumNumbers(root, 0);}private:int sumNumbers(TreeNode *root, int sum){if (!root) return 0;else if (!root->left && !root->right) return sum + root->val;else return sumNumbers(root->left, (root->val + sum) * 10) + sumNumbers(root->right, (root->val + sum) * 10);}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/sum-root-to-leaf-numbers/description//// Author : liuyubobobo/// Time : 2018-10-16#include <iostream>using namespace std;/// Recursion/// Time Complexity: O(n)/// Space Complexity: O(logn)/// 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 sumNumbers(TreeNode* root) {if(!root) return 0;int res = 0;dfs(root, 0, res);return res;}private:void dfs(TreeNode* node, int tnum, int& sum){tnum = tnum * 10 + node->val;if(!node->left && !node->right)sum += tnum;else{if(node->left)dfs(node->left, tnum, sum);if(node->right)dfs(node->right, tnum, sum);}}};int main() {return 0;}