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

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

Leetcode 113. Path Sum II

2019-11-14 12:59:00
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

For example: Given the below binary tree and sum = 22,

5 / / 4 8 / / / 11 13 4 / / / / 7 2 5 1

return

[ [5,4,11,2], [5,8,4,5]]

s思路: 1. 和Leetcode 112. Path Sum相似。區(qū)別是要列舉所有的路徑!基本思路還是PReorder,但是需要一個(gè)vector< int>把每次遍歷的數(shù)放入或者彈出,當(dāng)判斷path sum為所求,則把這個(gè)vector保存起來(lái)。

//方法1:recursive:class Solution {public: void helper(vector<vector<int>>&res,TreeNode* root,vector<int> cur,int sum) { // if(!root) return; cur.push_back(root->val);//中 if(!root->left&&!root->right){ if(root->val==sum)res.push_back(cur); return; } helper(res,root->left,cur,sum-root->val);//左 helper(res,root->right,cur,sum-root->val);//右 //cur.pop_back(); } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> res; //vector<int> cur; helper(res,root,{},sum); return res; }};//方法1:變形的做法.上面方法用vector<int> cur,這個(gè)方法用vector<int>&curclass Solution {public: void helper(vector<vector<int>>&res,TreeNode* root,vector<int>&cur,int sum) { // if(!root) return; cur.push_back(root->val);//中 if(!root->left&&!root->right){ if(root->val==sum)res.push_back(cur); //return; } helper(res,root->left,cur,sum-root->val);//左 helper(res,root->right,cur,sum-root->val);//右 cur.pop_back(); } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> res; vector<int> cur; helper(res,root,cur,sum); return res; }};//方法2:iterative.用stack,preorder,用cur和pre兩個(gè)指針。其實(shí)都是套路。class Solution {public: vector<vector<int>> pathSum(TreeNode* root, int sum) { stack<TreeNode*> ss; TreeNode* pnow=root,*pre=NULL; vector<vector<int>> res; vector<int> cur; int path=0; while(pnow||!ss.empty()){ while(pnow){ path+=pnow->val; cur.push_back(pnow->val); ss.push(pnow); pnow=pnow->left; } pnow=ss.top(); if(!pnow->left&&!pnow->right&&path==sum){ res.push_back(cur); } if(pnow->right&&pnow->right!=pre){ pnow=pnow->right; }else{ pre=pnow; path-=pnow->val; ss.pop(); cur.pop_back(); pnow=NULL; } } return res; }};
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 溧水县| 井研县| 苍梧县| 电白县| 工布江达县| 和顺县| 萨迦县| 忻城县| 马鞍山市| 鄄城县| 喜德县| 佛坪县| 百色市| 荆门市| 比如县| 泸水县| 鞍山市| 铁岭市| 广汉市| 辽源市| 乐至县| 苏尼特左旗| 钟祥市| 江达县| 沽源县| 南昌市| 棋牌| 普陀区| 德庆县| 贞丰县| 尼木县| 昭觉县| 福鼎市| 翁牛特旗| 轮台县| 毕节市| 金昌市| 武义县| 蒙山县| 金川县| 大渡口区|