Leetcode of depth-first search (DFS) Thematic -129. Roots to the leaf node digital sum (Sum Root to Leaf Numbers)

Leetcode of depth-first search (DFS) Thematic -129. Roots to the leaf node digital sum (Sum Root to Leaf Numbers)

Problem-solving depth-first search details, click


Given a binary tree, each node of which are stored a  0-9 number, 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 representing a digital  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: 
from the root to a leaf node of the path 1->2represents a number 12. 
From the root to a leaf node of the path 1->3represents the number 13. 
Thus, the digital sum = 12 + 13 = 25.

Example 2:

Input: [4,9,0,5,1] 
    4 
   / \ 
  90 
 / \ 
51 
Output: 1026 
explain: 
from the root to a leaf node of the path 4->9->5represents the number 495. 
From the root to a leaf node of the path 4->9->1represents the number 491. 
From the root to leaf node path 4->0represents the number 40. 
Thus, the digital sum + = 495 + 40 = 491 1026.

Analysis: search the entire tree, and the value of the current node has been stitching up, if the node is a leaf node, the value added ans go.
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int ans = 0;
    public int sumNumbers(TreeNode root) {
        if(root==null) return 0;
        dfs(root,"");
        return ans;
    }
    public void dfs(TreeNode node,String num){
        if(node==null){
            return;
        }
        
        if(node.left==null && node.right==null){
            ans+=Integer.valueOf(num+node.val);
            return;
        }
        dfs(node.left,num+node.val);
        dfs(node.right,num+node.val);
    }
}

 




 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11367092.html