Problem
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 number 123.
Find the total sum of all 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.
Code
int sn_r(TreeNode *root,int parent) { if(!root) return 0; int lsum = sn_r(root->left,10*parent + root->val); int rsum = sn_r(root->right,10*parent + root->val); if(lsum ==0 && rsum ==0) return (10*parent + root->val); return (lsum + rsum); } int sumNumbers(TreeNode *root) { // Note: The Solution object is instantiated only once and is reused by each test case. return sn_r(root,0); }
No comments:
Post a Comment