[Leetcode] sum root to leaf numbers

Source: Internet
Author: User

Question

Given a Binary Tree Containing digits from0-9Only, each root-to-leaf path cocould represent a number.

An example is the root-to-leaf path1->2->3Which represents the number123.

Find the total sum of all root-to-leaf numbers.

For example,

    1   /   2   3

The root-to-leaf path1->2Represents the number12.
The root-to-leaf path1->3Represents the number13.

Return the sum = 12 + 13 =25.

Answer

Recursive solution with tree

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int sumNumbers(TreeNode root) {        if(root==null){            return 0;        }        return sum(root,0);    }        public int sum(TreeNode node,int parentVal){        int sum=0;        int temp=parentVal*10+node.val;        if(node.left==null&&node.right==null){            sum=temp;        }        if(node.left!=null){            sum+=sum(node.left,temp);        }        if(node.right!=null){            sum+=sum(node.right,temp);        }        return sum;    }} 

--- EOF ---

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.