Leetcode 129. Sum Root to Leaf Numbers

xiaoxiao2021-03-01  6

文章作者:Tyan 博客:noahsnail.com  |   |  简书

1. Description

2. Solution

/** * 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 sumNumbers(TreeNode* root) { if(!root) { return 0; } int sum = 0; traverseSum(root, sum, 0); return sum; } private: void traverseSum(TreeNode* root, int& sum, int current) { current = current * 10 + root->val; if(!root->left && !root->right) { sum += current; return; } if(root->left) { traverseSum(root->left, sum, current); } if(root->right) { traverseSum(root->right, sum, current); } } };

Reference

https://leetcode.com/problems/sum-root-to-leaf-numbers/description/
转载请注明原文地址: https://www.6miu.com/read-3850022.html

最新回复(0)