Title:
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 .
Test Instructions:
Given a binary tree, which contains only 0-9 of the number elements, each path from the root node to the leaf node can represent a number.
For example, a path from the root node to the leaf node is 1->2->3 The number of delegates is 123 .
Find out all the numbers represented in the path from the root to the leaf node.
For example, given:
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 .
Algorithm Analysis:
Through recursion, the idea is clear, mainly to consider the recursive condition and the end condition. Look directly at the code, better understanding.
AC Code:
<span style= "Font-family:microsoft yahei;font-size:12px;" >/** * Definition for Binary tree * public class TreeNode {* int val, * TreeNode left, * TreeNode right; TreeNode (int x) {val = x;} *} *///is also recursive public class solution { int sum = 0; public int sumnumbers (TreeNode root) { if (root = null) return 0; Run (root, 0); return sum; } public void run (TreeNode root, int num) { num = ten * num + root.val; if (Root.left = = NULL && Root.right = = null) sum + = num; if (root.left! = null) run (root.left, num); if (root.right! = null) run (root.right, num);} } </span>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Sum Root to Leaf Numbers