解題心得
把 tree 給走訪一遍。若走到 left node 就把累計的加起來。
程式碼
class Solution { public: void helper(TreeNode* root, int& sum, int current) { current = current * 10 + root->val; if(root->left == nullptr && root->right == nullptr) { sum += current; cout << current << endl; return; } else { if(root->left) helper(root->left, sum, current); if(root->right) helper(root->right, sum, current); } } int sumNumbers(TreeNode* root) { int sum = 0; helper(root, sum, 0); return sum; } };
沒有留言:
張貼留言