Created
July 11, 2014 16:03
-
-
Save walkingtospace/0c08a6d5242f2b1bb37e to your computer and use it in GitHub Desktop.
sum-root-to-leaf-numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/ | |
int sumNumbers(TreeNode *root) { | |
if(!root) return 0; | |
vector<int> sum; | |
sum.push_back(root->val); | |
if(!root->left && !root->right) return root->val; | |
return sumNumbers(root->left, sum) + sumNumbers(root->right, sum); | |
} | |
int sumNumbers(TreeNode* node, vector<int> sum) { | |
if(!node) return 0; | |
sum.push_back(node->val); | |
if(!node->left && !node->right) { //leaf node | |
int temp=0; | |
for(int i= sum.size()-1; i >= 0 ; i--) temp += sum[i] * pow(10, (sum.size()-1)-i); | |
return temp; | |
} | |
return sumNumbers(node->left, sum) + sumNumbers(node->right, sum); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment