One. Problem Description
Given a binary tree, each node that are stored in a digital 0-9, from the root to each leaf node represents a number of paths.
For example, the path from the root to the leaf node 1-> 2-> 3 represents the number 123.
Calculated from the root to the leaf nodes generated by the sum of all the numbers.
Description: leaf node is a node has no child nodes.
Example 1:
Input: [1,2,3]
1
/ \
2 3
Output: 25
Explanation:
The path from the root to the leaf node 1-> 2 represents the number 12.
The path from the root to the leaf node 1-> 3 represents the number 13.
Thus, digital sum = 12 + 13 = 25.
Example 2:
Input: [4,9,0,5,1]
4
/ \
9 0
/ \
5 1
Output: 1026
Explanation:
The path from the root to the leaf node 4-> 9-> 5 represents the number 495.
The path from the root to the leaf node 4-> 9-> 1 represents the number 491.
The path from the root to the leaf node 4-> 0 represents the number 40.
Thus, digital sum = 495 + 491 + 40 = 1026.
two. Problem-solving ideas
Body idea: the method is recursive sequence traversal + solved.
Step a: Construction of a recursive function (root root node represents the current representative number from the root to the current node value)
Step two: the root node first determines whether there is a child node, if the value of the root node number * 10 + new child node into the recursive function until the child node is completed traversed, layer by layer returns all values.
three. Results of the
When execution: 1 ms, beat the 63.67% of all users in java submission
Memory consumption: 34.5 MB, defeated 47.62% of all users in java submission
four. Java code
class Solution { public int sumNumbers(TreeNode root) { if(root==null) { return 0; }else { return getNumber(root,root.val); } } public int getNumber(TreeNode root,int number) { if(root.left==null&&root.right==null) { return number; } int templeft=0; int tempright=0; if(root.left!=null) { templeft=getNumber(root.left,root.left.val+number*10); } if(root.right!=null) { tempright=getNumber(root.right,root.right.val+number*10); } return templeft+tempright; } }