Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

129. Sum Root to Leaf Numbers 🌟🌟

You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number.

Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer. A leaf node is a node with no children.

O(N) Time recursive

Code

class Solution{
    int ans = 0;
    void dfs(TreeNode *root, int val){
        if (!root) return;
        val *= 10;
        val += root->val;

        if (root->left == NULL && root->right == NULL){
            ans += val;
            return;
        }
        dfs(root->left, val);
        dfs(root->right, val);
    }

public:
    int sumNumbers(TreeNode *root){
        if (!root) return 0;
        dfs(root, 0);
        return ans;
    }
};

Useful Comment:

  1. List of problems you need to master the concept :

If you find more problems, please comment it below :)