1. 程式人生 > >129. Sum Root to Leaf Numbers(Tree)

129. Sum Root to Leaf Numbers(Tree)

連結: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;
};