C language recursion Root node numbers to the leaves and

Title 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.

 

Examples

Input: [ 1 , 2 , 3 ]
     1 
   / \
   2    3 
Output: 25 
Explanation: 
from the root to a leaf node route 1 -> 2 represents the number 12 . 
From the root to a leaf node route 1 -> 3 represents the number 13 . 
Thus, the digital Total = 12 + 13 = 25 .
Input: [ 4 , 9 , 0 , 5 , 1 ]
     4 
   / \
   9    0
  / \
 5    1 
Output: 1026 
Explanation: 
from the root to the leaf node Path 4 -> 9 -> 5 represents the number 495 . 
From the root to a leaf node path . 4 -> . 9 -> 1 represents the number 491 . 
from the root to a leaf node of the path . 4 -> 0 represent numbers 40 . 
Thus, the digital sum = 495 + 491 +40 = 1026.

 

Questions asked

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 
10 int sumNumbers(struct TreeNode* root){
11 
12 }

 

answer

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 
10 int work(struct TreeNode* r,int count){
11     count=count*10+r->val;
12     if(r->left==NULL&&r->right==NULL)return count;
13     if(r->left==NULL)return work(r->right,count);
14     if(r->right==NULL)return work(r->left,count);
15     return work(r->left,count)+work(r->right,count);
16 }
17 
18 int sumNumbers(struct TreeNode* root){
19     if(root==NULL)return 0;
20     return work(root,0);
21 }

 

Binary data and comprises a recursive digital transmission and is therefore termed a recursive function.

Cumulative number is equal to the current node left child node and the cumulative figures and right child.

Return that left child and right child nodes are empty when.

 

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/sum-root-to-leaf-numbers
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

 

Guess you like

Origin www.cnblogs.com/shi-champion/p/11678605.html