Tree--sum-root-to-leaf-numbers

Source: Internet
Author: User

Topic:

Binary tree Each node contains 0-9 digits, such as a root-to-leaf path of h1->2->3, then the path is 123, and the total path of the two fork tree is obtained.

,

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.

Idea: Exhaustive traversal of the binary tree, each time traversing to the leaf node will be added to the totalsum of the path, and finally return to Totalsum.


The code is as follows:

/**
 * Definition for binary Tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode (int x) {val = x;}
 *} */Public
class Solution {
    private int totalsum=0;
    
    public int sumnumbers (TreeNode root) {
        if (root = null)
            return 0;
           Pathsum (root,0);
        return totalsum;
        
        }
    
    public void Pathsum (TreeNode root,int presum)//presum the and of the path before the node;
        {
        if (Root.left = = null&& Root.right = = null)
            totalsum+=presum*10+root.val;//each traversal to the root node, adding the path to the totalsum;
        
        if (root.left!=null)
            pathsum (root.left,presum*10+root.val);
        if (root.right!=null)
            pathsum (root.right,presum*10+root.val);
    }
}


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.