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 path1->2
represents a number12
. From the root to a leaf node of the path1->3
represents the number13
. 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 path4->9->5
represents the number 495. From the root to a leaf node of the path4->9->1
represents the number 491. From the root to leaf node path4->0
represents the number 40. Thus, the digital sum + = 495 + 40 = 4911026
.
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); } }