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);
}
}