[LEETCODE] Sum Root to Leaf Numbers
LINK:http://leetcode.com/onlinejudge#question_129
大意:题目给出一颗二叉树,要求你求出从根到叶子的一条路径上所有数字构成数的和
1 / \ 2 3
12 + 13 = 25
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
二叉树遍历 简单递归题?
1 class Solution { 2 public: 3 int tot; 4 void gao(TreeNode *p, int sum){ 5 if(p ==NULL) 6 return; 7 if(p->left == NULL && p->right ==NULL){ 8 tot += sum*10 + p->val; 9 } 10 if(p->left!=NULL){ 11 gao(p->left, sum*10+p->val); 12 } 13 if(p->right!=NULL){ 14 gao(p->right, sum*10+p->val); 15 } 16 } 17 int sumNumbers(TreeNode *root) { 18 // Start typing your C/C++ solution below 19 // DO NOT write int main() function 20 tot = 0; 21 gao(root,0); 22 return tot; 23 } 24 };

浙公网安备 33010602011771号