题解 | #二叉树根节点到叶子节点的所有路径和#

二叉树根节点到叶子节点的所有路径和

http://www.nowcoder.com/practice/185a87cd29eb42049132aed873273e83

 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    int res = 0;
    void sn(TreeNode* root, int p) {
        // write code here
        if(!root){
            return;
        }
        if(root->left){
            sn(root->left, p*10 + root->val);
        }
        if(root->right){
            sn(root->right, p*10 + root->val);
        }
        if(!root->left&&!root->right){
            res += p*10 + root->val;
        }
        
    }
    int sumNumbers(TreeNode* root) {
        // write code here
        sn(root, 0);
        return res;
    }
};
全部评论

相关推荐

每晚夜里独自颤抖:你cet6就cet6,cet4就cet4,你写个cet证书等是什么意思。专业技能快赶上项目行数,你做的这2个项目哪里能提现你有这么多技能呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务