【leetcode】129. Sum Root to Leaf Numbers
来源:互联网 发布:数据加工处理标准 编辑:程序博客网 时间:2024/06/06 01:33
「思路」
用a,b分别记录右子树和左子树当前的值,在root没有左右子树时,将最终取得的a或b的值加给ans。当仅有右子树时,a在加上当前root的值和从上一层传递来的数据(由于不知道上一层是从a还是b传来的,所以a,b都要加上),再*10。指针向右子树继续向下传递(注意,仅从右子树向下传递时,b要清0,以防重复计算)。同理的仅有左子树的情况。当左右子树都有时,a b都要重新用以上方法计算。
「运行结果」
class Solution {public: int ans=0; int sumNumbers(TreeNode* root) { if(!root) return ans; sumnum(root,0,0); return ans; } void sumnum(TreeNode* root,int a,int b) { if(!root->left && !root->right) { ans=ans+a+b+root->val; return; } else if(!root->left && root->right) { a=(a+b+root->val)*10; sumnum(root->right,a,0); } else if(root->left && !root->right) { b=(b+a+root->val)*10; sumnum(root->left,0,b); } else { int i=a; a=(a+b+root->val)*10; b=(i+b+root->val)*10; sumnum(root->left,0,b); sumnum(root->right,a,0); } }};
完成之后,继续去看了leetcode上更加简洁的算法,自己也按照同样的思路做了一遍,这种算法虽然时间上没有提升,但是代码量减少了也算是一种进步,如下:
class Solution {public: int sumNumbers(TreeNode* root) { return sumnum(root,0); } int sumnum(TreeNode* root,int ans) { if(!root) return 0; if(!root->left && !root->right) { return ans+root->val; } int temp=(ans+root->val)*10; return sumnum(root->left,temp)+sumnum(root->right,temp); }};
下一种是leetcode上运行最快的代码,作为借鉴,如下:
class Solution {public: void digui(TreeNode * root, int temp) { if (root->left == NULL && root->right == NULL) {ans+=temp;return;} if (root->left) { digui(root->left,temp*10+root->left->val); } if (root->right) { digui(root->right,temp*10+root->right->val); } return ; } int sumNumbers(TreeNode* root) { ans = 0; if (root == NULL) return ans; digui(root,root->val) ; return ans; } int ans;};
阅读全文
0 0
- [LeetCode]129.Sum Root to Leaf Numbers
- LeetCode 129. Sum Root to Leaf Numbers
- [leetcode] 129.Sum Root to Leaf Numbers
- 【leetcode】129. Sum Root to Leaf Numbers
- [leetcode] 129. Sum Root to Leaf Numbers
- [LeetCode]129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers LeetCode
- [LeetCode]129. Sum Root to Leaf Numbers
- leetcode 129. Sum Root to Leaf Numbers
- Leetcode 129. Sum Root to Leaf Numbers
- LeetCode *** 129. Sum Root to Leaf Numbers
- LeetCode-129.Sum Root to Leaf Numbers
- LeetCode 129. sum-root-to-leaf-numbers
- LeetCode - 129. Sum Root to Leaf Numbers
- LeetCode 129. Sum Root to Leaf Numbers
- [leetcode] 129. Sum Root to Leaf Numbers
- [LeetCode] 129. Sum Root to Leaf Numbers
- Leetcode-129. Sum Root to Leaf Numbers
- HDU4355 三分
- 判断某个字符串是否是合法IP
- 拦截器,过滤器,监听器的区别
- 前馈神经网络,BP算法
- Angular 2 HostListener & HostBinding
- 【leetcode】129. Sum Root to Leaf Numbers
- Cookie, LocalStorage 与 SessionStorage
- 666666
- cleanmymac 3.8.4 免费破解激活码
- EarMaster 6 Pro 中文破解版练耳大师 音乐人士必备工具 序列号
- 31 Three.js的特殊光源镜头光晕(lens flare)
- 开始我的csdn博客
- Java-Java5.0泛型解读
- 操作系统-进程和线程介绍、死锁处理