LeetCode June Challenge - Day 26

Problem: LeetCode June Challenge - Day 26

Ideas

  1. Do a DFS. At a certain node, the current value is the value of the previous node multiplied by 10 plus the value of the current node.

Solution:

class Solution {
    int ans;
    int cur;
    void rec(TreeNode* root){
        cur = cur*10 + root->val;
        if(root->right == NULL && root->left == NULL)
            ans += cur;
        if(root->left != NULL) rec(root->left);
        if(root->right != NULL) rec(root->right);
        cur = (cur - root->val)/10;
    }
    public:
    int sumNumbers(TreeNode* root) {
        if(root == NULL) return 0;
        ans = cur = 0;
        rec(root);
        return ans;
    }
};