麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

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

Leetcode 113. Path Sum II

2019-11-14 12:59:00
字體:
供稿:網(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,但是需要一個vector< int>把每次遍歷的數(shù)放入或者彈出,當(dāng)判斷path sum為所求,則把這個vector保存起來。

//方法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,這個方法用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兩個指針。其實(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ā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 免费淫视频| 男人的天堂视频网站 | 精品三区视频 | 爱爱插插视频 | 中国女人内谢8xxxxxx在 | 亚洲最黄视频 | 精品一区二区久久久久 | 香蕉成人在线观看 | 日本在线视 | 久久久久久久久久久综合 | 成人福利软件 | 久久久无码精品亚洲日韩按摩 | 国产亚洲精品久久午夜玫瑰园 | 欧美午夜网 | 九九热这里只有精品8 | 国产pron| 免费亚洲视频在线观看 | 日夜操天天干 | 国产精品久久久久久久久久电影 | 久久福利剧场 | 在线免费黄色网 | 一级一级一级毛片 | 国产精品久久久久久婷婷天堂 | 国产一级午夜 | 亚洲自拍第二页 | av在线免费观看不卡 | 成人福利在线观看 | 国产一区二区久久精品 | 日本在线不卡一区二区三区 | 草草视频在线播放 | 激情大乳女做爰办公室韩国 | 99成人在线| 91丨九色丨国产在线观看 | 欧美激情猛片xxxⅹ大3 | 久久久久亚洲视频 | 国产免费传媒av片在线 | 蜜桃免费在线 | 天天草天天干天天射 | 亚洲码无人客一区二区三区 | www国产成人免费观看视频,深夜成人网 | 国产精品无码久久久久 |