Sum Root to Leaf Numbers

https://leetcode.com/problems/sum-root-to-leaf-numbers/description/

Given a binary tree containing digits from 0-9 only, 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.

Thoughts

和pathSum一个路数,只是这里psum不再只是加上,而是有个特殊处理。

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 res = 0;
    int sumNumbers(TreeNode* root) {
        dfs(root, 0);
        return res;
    }
    
    void dfs(TreeNode *cur, int psum) {
        if (cur == NULL) return;
        psum = psum * 10 + cur->val;
        if (cur->left == NULL && cur->right == NULL) res += psum;
        dfs(cur->left, psum);
        dfs(cur->right, psum);
    }
};

Analysis

时间复杂度为一次遍历O(n)

Ver.2

和pathSum一个路数,都是记录从root往下的psum, 只是这里psum不再只是加上,而是有个特殊处理。

Last updated

Was this helpful?