Sum Root to Leaf Numbers

Given a binary tree containing digits from 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 rootint res) {

        // if tree is empty
        if (root == null)
            return 0;

        // update the value
        res = (res * 10 + root.val);

        // if leaf node then return the resulted sum
        if (root.left == null && root.right == null)
            return res;

        // else call for lefr and right subtree
        return 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 valTreeNode leftTreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;
//struct for treenode
struct 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 empty
        if(root==NULL)
               return 0;

        //update the value
        res=(res*10+root->data);

        //if leaf node then return the resulted sum
        if(root->left==NULL&&root->right==NULL)
               return res;

         //else call for lefr and right subtree
        return 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