129. Sum Root to Leaf Numbers(Tree)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tangyuanzong/article/details/85374860

链接:https://leetcode.com/problems/sum-root-to-leaf-numbers/

题目:一条roo->leaf路径代表一个整数,求所有整数之和

思路:先序遍历

代码:

class Solution {
public:
    void pre(TreeNode *root,int sum){
         if(!root) return;
        
         if(!root->left&&!root->right) {
             ret +=(sum *10 + root->val);
             return ;
         }
        
         pre(root->left,root->val + sum * 10);
         pre(root->right,root->val + sum * 10);
    }
    
    int sumNumbers(TreeNode* root) {
        ret = 0;
        pre(root,0);
        return ret;
    }
private:
    int ret;
};

猜你喜欢

转载自blog.csdn.net/tangyuanzong/article/details/85374860
今日推荐