国产探花免费观看_亚洲丰满少妇自慰呻吟_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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 鸡泽县| 靖州| 繁昌县| 抚州市| 东兴市| 合山市| 赣州市| 临西县| 馆陶县| 芜湖市| 赤城县| 徐汇区| 长岭县| 富阳市| 蒙城县| 图们市| 辉县市| 台州市| 沽源县| 婺源县| 洛阳市| 玛纳斯县| 万山特区| 民权县| 清镇市| 五原县| 临武县| 鲁甸县| 化州市| 通海县| 新乡市| 福清市| 拜泉县| 修文县| 武宁县| 庆阳市| 涿州市| 准格尔旗| 巨野县| 白玉县| 崇信县|