Given a binary tree containing digits from only 0-9 , each root-to-leaf path could represent a number.
An example is the Root-to-leaf path 1->2->3 which represents the number 123 .
Find The total sum of all root-to-leaf numbers.
For example,
1 / 2 3
The Root-to-leaf path 1->2 represents the number 12 .
The Root-to-leaf path 1->3 represents the number 13 .
Return the sum = + = 25 .
Title: To a binary tree, each node is a number between 0-9, from the root node to the leaf node represents a number, all of these numbers and.
Problem-solving ideas: This problem should be a study of DFS, can be directly DFS solution, or in the queue can also be used to do, the recent problem is no state, head a group of paste.
Public intsumnumbers (TreeNode root) {returnSUM (root,0); } Public intSUM (TreeNode node,intsum) { if(node==NULL){ return0; } if(node.left==NULL&&node.right==NULL) {sum=sum*10+Node.val; returnsum; } returnSUM (node.left,sum*10+node.val) +sum (node.right,sum*10+node.val); }
Sum Root to Leaf Numbers--leetcode