[LeetCode 129] Find the sum of numbers from root to leaf node (medium) dfs

Given a binary tree, each node of it stores a number from 0-9, and each path from the root to the leaf node represents a number.

For example, the path 1->2->3 from the root to the leaf node represents the number 123.

Calculate the sum of all the numbers generated from the root to the leaf nodes.

Explanation: A leaf node refers to a node without child nodes.

Example 1:

输入: [1,2,3]
    1
   / \
  2   3
输出: 25

Explanation: The
path from the root to the leaf node 1->2 represents the number 12. The
path from the root to the leaf node 1->3 represents the number 13.
Therefore, the sum of the numbers = 12 + 13 = 25.
Example 2:

输入: [4,9,0,5,1]
    4
   / \
  9   0
 / \
5   1
输出: 1026

Explanation: The
path from the root to the leaf node 4->9->5 represents the number 495. The
path from the root to the leaf node 4->9->1 represents the number 491. The
path from the root to the leaf node 4->0 represents the number 40.
Therefore, the sum of the numbers = 495 + 491 + 40 = 1026.


Code:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    int ans=0;

    void dfs(TreeNode* root,int sum)
    {
    
    
        if(root->left==NULL && root->right==NULL)  //叶子
        {
    
    
            ans += sum; //累加数字和
            return;
        }

        if(root->left)  dfs(root->left,sum*10+root->left->val); // 左子树
        if(root->right) dfs(root->right,sum*10+root->right->val); // 右子树
    }

    int sumNumbers(TreeNode* root) {
    
    
        if(root==NULL) return 0; //防止空指针
        dfs(root,root->val);
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/weixin_45260385/article/details/110098953