Given a binary tree containing digits from
An example is a root-to-leaf path
0-9
only, each root-to-leaf path could represent a number.An example is a root-to-leaf path
1->2->3
which represents the number 123
.Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
Example:
Input: [1,2,3]
1
/ \
2 3
Output: 25
Approach
Java
public class SumRootLeafNumbers {public static void main(String[] args) {TreeNode root = new TreeNode(1);root.left = new TreeNode(2);root.right = new TreeNode(3);System.out.println(sumNumbers(root));}static int sumNumbers(TreeNode root) {int res = 0;res = sum(root, 0);return res;}static int sum(TreeNode root, int res) {// if tree is emptyif (root == null)return 0;// update the valueres = (res * 10 + root.val);// if leaf node then return the resulted sumif (root.left == null && root.right == null)return res;// else call for lefr and right subtreereturn sum(root.left, res) + sum(root.right, res);}}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data=data;this->left=NULL;this->right=NULL;}};int sum(TreeNode *root,int res){//if tree is emptyif(root==NULL)return 0;//update the valueres=(res*10+root->data);//if leaf node then return the resulted sumif(root->left==NULL&&root->right==NULL)return res;//else call for lefr and right subtreereturn sum(root->left,res)+sum(root->right,res);}int sumNumbers(TreeNode* root){int res=0;res=sum(root,0);return res;}int main(){TreeNode *root=new TreeNode(1);root->left=new TreeNode(2);root->right=new TreeNode(3);cout<<sumNumbers(root);return 0;}
No comments:
Post a Comment