LeetCode: Sum Root to Leaf Numbers

思路:还是深度搜索树,当前节点如果是叶子节点,则计算出从根到叶子节点表示的数(这个数在路径中一直动态存储),加到总和中。

code:

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


你可能感兴趣的:(LeetCode: Sum Root to Leaf Numbers)