国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 德保县| 东城区| 江陵县| 上高县| 常德市| 石景山区| 南宁市| 瑞金市| 东兰县| 观塘区| 红河县| 盐池县| 舞钢市| 德阳市| 连江县| 青龙| 廉江市| 嘉兴市| 永昌县| 土默特左旗| 普洱| 兴国县| 郓城县| 元谋县| 正阳县| 罗定市| 项城市| 宾川县| 鹰潭市| 河西区| 三亚市| 新绛县| 霍林郭勒市| 城口县| 迭部县| 清流县| 龙口市| 竹溪县| 临清市| 临清市| 寿宁县|