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

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

Leetcode 199. Binary Tree Right Side View

2019-11-10 19:23:24
字體:
來(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ù)都要寫(xiě)一遍在vector中,而bfs只有滿(mǎn)足條件的才往里寫(xiě)! 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; }};
發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 陆河县| 孙吴县| 吉首市| 新田县| 张掖市| 巨鹿县| 永昌县| 兴文县| 碌曲县| 双辽市| 顺昌县| 铅山县| 安义县| 积石山| 永兴县| 余姚市| 榆林市| 南阳市| 镇江市| 西宁市| 乌海市| 探索| 甘南县| 崇左市| 台湾省| 苍溪县| 哈密市| 灵丘县| 徐闻县| 青海省| 广丰县| 肃宁县| 剑阁县| 宿松县| 丽水市| 咸丰县| 临沧市| 页游| 保山市| 稻城县| 敦煌市|