[leetcode]Sum Root to Leaf Numbers

来源:互联网 发布:张若昀长相知乎 编辑:程序博客网 时间:2024/06/16 04:39

//树的遍历。切记,传值时候需要&

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode *root) {
        int sum = 0;
        //int presum=0;
        treesum(root,0,sum);
        return sum;
    }
    void treesum(TreeNode* root,int presum,int &sum)
    {
        if(root==NULL)return;
        presum=root->val+presum*10;
        if(root->left==NULL&&root->right==NULL)
        {sum+=presum;presum=0;return;}//
        treesum(root->left,presum,sum);
        treesum(root->right,presum,sum);
    }
};

0 0