c++ dfs solution.


  • 0
    class Solution {
    public:
      int sumNumbers(TreeNode* root) {
        vector<int> nums;
        int ret = 0;
    
        if (root == NULL)
        {
          return ret;
        }
        dfs(root, nums, 0);
        for (auto i : nums)
        {
          ret += i;
        }
        return ret;
      }
      void dfs(TreeNode *root, vector<int> &nums, int num)
      {
        num = num * 10 + root -> val;
        if (root -> left != NULL)
        {
          dfs(root -> left, nums, num);
        }
        if (root -> right != NULL)
        {
          dfs(root -> right, nums, num);
        }
        if (root -> left == NULL && root -> right == NULL)
        {
          nums.push_back(num);
        }
      }
    };
    

Log in to reply
 

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