129. Sum Root to Leaf Numbers
来源:互联网 发布:iframe 跨域调用js 编辑:程序博客网 时间:2024/06/09 18:53
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 = 25.
递归解法:
class Solution {public: int sum=0; void find(TreeNode *root,int t){ if(root->left==NULL&&root->right==NULL){ sum+=t*10+root->val; }else{ if(root->left!=NULL) find(root->left,t*10+root->val); if(root->right!=NULL) find(root->right,t*10+root->val); } } int sumNumbers(TreeNode* root) { if(root==NULL)return sum; else{ find(root,0); return sum; } }};
非递归:
class Solution {public: int sumNumbers(TreeNode* root) { int sum=0,t=0; if(root==NULL)return sum; stack<TreeNode*>st; map<TreeNode*,bool>visit; st.push(root); visit[root]=true; t=root->val; while(!st.empty()){ TreeNode *top=st.top(); if(top->left!=NULL&&visit[top->left]==false){ st.push(top->left); visit[top->left]=true; t=t*10+top->left->val; continue; } else if(top->right!=NULL&&visit[top->right]==false){ st.push(top->right); visit[top->right]=true; t=t*10+top->right->val; continue; } else if(top->left==NULL&&top->right==NULL){ sum+=t; } st.pop(); t=t/10; } return sum; }};
0 0
- [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】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
- 129. Sum Root to Leaf Numbers
- Leetcode 129. Sum Root to Leaf Numbers
- 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
- 129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- MongoDB插入文档
- Java多线程编程1----基础知识--暂停线程(sleep(),yield(),join()详解)
- AngularJS快速开始
- 第十一周 阅读程序(1)
- Bootstrap 栅格系统
- 129. Sum Root to Leaf Numbers
- MongoDB更新文档
- 常用图像插值算法分析与比较
- zabbix 添加主机成功失败判断
- 动态规划—Problem L
- linux基础之常用命令(2)
- [疯狂Java]I/O:其它自定义序列化的方法(transient、writeReplace、readResolve、Externalizable)
- UILabel加下划线
- 手机端兼容代码js