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

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

Leetcode 129. Sum Root to Leaf Numbers

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

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; }};
上一篇:表單

下一篇:linux內核目錄結構

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 蓬溪县| 留坝县| 昂仁县| 古蔺县| 黄平县| 宝兴县| 长白| 泗水县| 浮山县| 英德市| 杨浦区| 济源市| 阿鲁科尔沁旗| 青岛市| 清水河县| 博客| 宣化县| 册亨县| 桐庐县| 玛多县| 辽宁省| 永仁县| 漠河县| 平湖市| 东港市| 黎城县| 循化| 东宁县| 黄骅市| 潼关县| 连南| 黄平县| 瓦房店市| 河北省| 延津县| 阿图什市| 青川县| 新巴尔虎左旗| 伊宁县| 四平市| 苗栗县|