这些小活动你都参加了吗?快来围观一下吧!>>
电子产品世界 » 论坛首页 » 嵌入式开发 » STM32 » sum-root-to-leaf-numbers

共1条 1/1 1 跳转至

sum-root-to-leaf-numbers

高工
2018-01-29 13:42:38     打赏

Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path1->2->3which represents the number123.

Find the total sum of all root-to-leaf numbers.



For example,

    1
   / \
  2   3


The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.

Return the sum = 12 + 13 =25.


思路:

先序遍历的思想(根左右)+数字求和(每一层都是上层和*10+当前值)


[cpp] view plain copy
  1. class Solution  

  2. {  

  3. public:  

  4.       

  5.     int sumNumbers(TreeNode* root)  

  6.     {  

  7.         int sum = 0;  

  8.         if (root==NULL)  

  9.         {  

  10.             return sum;  

  11.         }  

  12.   

  13.         return preorderSumNum(root, sum);  

  14.     }  

  15.   

  16.     int preorderSumNum(TreeNode* root,  int sum)  

  17.     {  

  18.         if (root==NULL)  

  19.         {  

  20.             return 0;  

  21.         }  

  22.   

  23.         sum = sum * 10 + root->val;  

  24.         if (root->left==NULL && root->right==NULL)  

  25.         {  

  26.             return sum;  

  27.         }  

  28.   

  29.         return preorderSumNum(root->left, sum) + preorderSumNum(root->right. sum);  

  30.     }  

  31. }; 




共1条 1/1 1 跳转至

回复

匿名不能发帖!请先 [ 登陆 注册 ]