您的位置:首页 > 其它

Sum Root to Leaf Numbers

2013-04-10 17:51 316 查看
和剑指offer里和为K的相似,这儿使用了霍纳法则来做的,很方便。

/**
 * 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 sum,res;
    int sumNumbers(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(!root) return 0;
        res=sum=0;
        dfs(root);
        return res;
    }
    void dfs(TreeNode *root){
        if(!root) return;
        sum=sum*10+root->val;
        if(!root->left&&!root->right)
            res+=sum;//这儿不能return
        if(root->left!=NULL)
            dfs(root->left);
        if(root->right!=NULL)
            dfs(root->right);
        sum=(sum-root->val)/10;//回溯
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: