美文网首页Leetcode
Leetcode 129. Sum Root to Leaf N

Leetcode 129. Sum Root to Leaf N

作者: SnailTyan | 来源:发表于2018-09-20 18:22 被阅读1次

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

    1. Description

    Sum Root to Leaf Numbers

    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

    1. https://leetcode.com/problems/sum-root-to-leaf-numbers/description/

    相关文章

      网友评论

        本文标题:Leetcode 129. Sum Root to Leaf N

        本文链接:https://www.haomeiwen.com/subject/ndynnftx.html