国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Leetcode 129. Sum Root to Leaf Numbers

2019-11-14 09:04:43
字體:
來源:轉載
供稿:網友

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.

s思路: 1. 樹的問題,根本就是遍歷。這道題一看肯定不能用bfs,因為要找到從root到leaf的數就需要dfs來找,遍歷順序是首先根,再左,后右,故:pre-order. 2. 要求和,則需要一個變量來表示這個最后的和;同時還需要一個變量表示目前從root到leaf的數。

//方法1:recursive來做,簡單。class Solution {public: void helper(TreeNode* root,int cur,int&sum){ if(!root) return; cur=cur*10+root->val;//根 if(!root->left&&!root->right){ sum+=cur; return; } helper(root->left,cur,sum);//左 helper(root->right,cur,sum);//右 } int sumNumbers(TreeNode* root) { // int sum=0; helper(root,0,sum); return sum; }};//方法2:iterative:pre-order,stack,兩個指針pre,pnow.class Solution {public: int sumNumbers(TreeNode* root) { stack<TreeNode*> ss; TreeNode* pnow=root,*pre=NULL; int sum=0,cur=0; while(pnow||!ss.empty()){ while(pnow){ cur=cur*10+pnow->val; ss.push(pnow); pnow=pnow->left; } pnow=ss.top(); if(!pnow->left&&!pnow->right) sum+=cur; if(pnow->right&&pnow->right!=pre){ pnow=pnow->right; }else{ pre=pnow; cur/=10; pnow=NULL; ss.pop(); } } return sum; }};
上一篇:ChucK初步(4)

下一篇:HashMap和HashTable

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 揭阳市| 醴陵市| 兰溪市| 奉节县| 马边| 太保市| 六盘水市| 互助| 涿鹿县| 弋阳县| 新平| 菏泽市| 藁城市| 新干县| 通山县| 綦江县| 阿拉善右旗| 垫江县| 嵩明县| 石屏县| 谷城县| 登封市| 枝江市| 乐安县| 含山县| 甘洛县| 云安县| 屯留县| 泗阳县| 宁德市| 定日县| 元氏县| 和平区| 庆云县| 平原县| 平远县| 绿春县| 五常市| 靖安县| 洛南县| 尉氏县|