首页 > 学院 > 开发设计 > 正文

129. Sum Root to Leaf Numbers

2019-11-08 03:21:08
字体:
来源:转载
供稿:网友

简单题,递归就ok

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int sum; void thesum(TreeNode* root, int n){ if(root -> left == NULL && root -> right == NULL){ sum = sum + n * 10 + root -> val; return ; } if(root -> left != NULL) thesum(root -> left, n * 10 + root -> val); if(root -> right != NULL) thesum(root -> right, n * 10 + root -> val); } int sumNumbers(TreeNode* root) { if(root == NULL) return 0; sum = 0; thesum(root, 0); return sum; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表