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

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

Leetcode 129. Sum Root to Leaf Numbers

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

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; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 左贡县| 淮安市| 萝北县| 塔河县| 武山县| 大理市| 镇平县| 定边县| 四平市| 吉林市| 沙河市| 三河市| 娱乐| 临西县| 游戏| 潢川县| 依兰县| 乐山市| 隆林| 富川| 井冈山市| 阳春市| 瑞昌市| 巧家县| 昆山市| 石林| 阿拉善右旗| 修武县| 河池市| 庆城县| 吴忠市| 喀什市| 曲周县| 禄丰县| 南平市| 综艺| 长春市| 象山县| 孟津县| 固安县| 阿巴嘎旗|