Standard DFS solution in C++


  • 0
    J
    class Solution {
    public:
        int sumNumbers(TreeNode* root) {
            int res = 0, one = 0;
            if(!root)
                return 0;
            bfs(res, root, one);
            return res;
        }
        
        void bfs(int& res, TreeNode* cur, int& one) {
            if(cur && !cur->left && !cur->right) {
                one = one * 10 + cur->val;
                res += one;
                return;
            }
            one = one * 10 + cur->val;
            int tp0 = one, tp1 = one;
            if(cur->left)
                bfs(res, cur->left, tp0);
            if(cur->right)
                bfs(res, cur->right, tp1);
        }
    };
    

    whenever the node is the last node, add the value of current node to results.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.