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

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

Leetcode 199. Binary Tree Right Side View

2019-11-10 18:56:09
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example: Given the following binary tree,

1 <--- / /2 3 <--- / / 5 4 <---

You should return [1, 3, 4].

s思路: 1. 樹(shù)的問(wèn)題,根本是遍歷。這道題,站在右邊,看到的是一層一層的,那么用bfs,用queue來(lái)存每一層的數(shù),然后把每一層最后一個(gè)數(shù)輸出即可! 2. 如果非要用dfs來(lái),怎么辦?這樣的困境,之前也遇到過(guò)。回憶一下,發(fā)現(xiàn)居然有一個(gè)套路,可以讓dfs同樣實(shí)現(xiàn)bfs才能干的活。這個(gè)套路是這樣的:設(shè)置一個(gè)level變量來(lái)跟蹤目前變量所在的層數(shù),如果這個(gè)層數(shù)比vector的size大,那就說(shuō)明第一次遇到,那么就需要resize vector來(lái)保存這個(gè)數(shù);如果這個(gè)層數(shù)比vector的size小,說(shuō)明以前遇到過(guò),而且這個(gè)數(shù)在左側(cè),因此直接覆蓋這個(gè)數(shù)在vector中的值。這樣,最后在vector中留下來(lái)的數(shù)就是從右側(cè)看到的數(shù)。通過(guò)描述這個(gè)過(guò)程,發(fā)現(xiàn)dfs每個(gè)數(shù)都要寫一遍在vector中,而bfs只有滿足條件的才往里寫! 3. 為啥不讓找從左側(cè)看到的樹(shù)呢?因?yàn)樘菀琢耍械谋闅v都是從左邊開(kāi)始。反而,從右邊看的視圖不容易得到。

//方法1:bfs,queueclass Solution {public: vector<int> rightSideView(TreeNode* root) { // vector<int> res; if(!root) return res; queue<TreeNode*> QQ; TreeNode* cur=root; qq.push(cur); while(!qq.empty()){ int sz=qq.size(); for(int i=0;i<sz;i++){ cur=qq.front(); qq.pop(); if(i==sz-1) res.push_back(cur->val); if(cur->left) qq.push(cur->left); if(cur->right) qq.push(cur->right); } } return res; }};//方法2:dfs,recursive,in-orderclass Solution {public: void helper(TreeNode* root,vector<int>&res,int level){ if(!root) return; if(res.size()<level+1){ res.resize(level+1); } res[level]=root->val; //根 helper(root->left,res,level+1);//左 helper(root->right,res,level+1);//右 } vector<int> rightSideView(TreeNode* root) { // vector<int> res; helper(root,res,0); return res; }};
上一篇:A+B (II)

下一篇:A1089. Insert or Merge (25)

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 木里| 博乐市| 丰都县| 资中县| 宜黄县| 墨江| 炎陵县| 沧州市| 哈尔滨市| 重庆市| 稻城县| 新沂市| 乐至县| 南木林县| 永德县| 广丰县| 盐池县| 桐梓县| 昔阳县| 林周县| 惠州市| 绥江县| 顺平县| 荆门市| 北碚区| 得荣县| 长垣县| 泸水县| 东兰县| 渭南市| 酉阳| 苗栗县| 黄陵县| 新乡县| 新化县| 临漳县| 青浦区| 凤凰县| 四会市| 伊通| 如东县|