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

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

Leetcode 129. Sum Root to Leaf Numbers

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

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; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 曲水县| 张家川| 东阿县| 开平市| 九江市| 偏关县| 宁明县| 宁国市| 岑溪市| 婺源县| 灌南县| 方正县| 突泉县| 鹿泉市| 麻江县| 吉安县| 丰台区| 资阳市| 鹤峰县| 余干县| 夹江县| 灵寿县| 阿鲁科尔沁旗| 德清县| 达孜县| 玛曲县| 柘荣县| 武宣县| 治县。| 滨州市| 宁都县| 乡城县| 资源县| 田林县| 新建县| 大同市| 永仁县| 宿州市| 同仁县| 青冈县| 安龙县|