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

首頁 > 學院 > 開發設計 > 正文

Leetcode 199. Binary Tree Right Side View

2019-11-10 19:59:23
字體:
來源:轉載
供稿:網友

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. 樹的問題,根本是遍歷。這道題,站在右邊,看到的是一層一層的,那么用bfs,用queue來存每一層的數,然后把每一層最后一個數輸出即可! 2. 如果非要用dfs來,怎么辦?這樣的困境,之前也遇到過?;貞浺幌?,發現居然有一個套路,可以讓dfs同樣實現bfs才能干的活。這個套路是這樣的:設置一個level變量來跟蹤目前變量所在的層數,如果這個層數比vector的size大,那就說明第一次遇到,那么就需要resize vector來保存這個數;如果這個層數比vector的size小,說明以前遇到過,而且這個數在左側,因此直接覆蓋這個數在vector中的值。這樣,最后在vector中留下來的數就是從右側看到的數。通過描述這個過程,發現dfs每個數都要寫一遍在vector中,而bfs只有滿足條件的才往里寫! 3. 為啥不讓找從左側看到的樹呢?因為太容易了,所有的遍歷都是從左邊開始。反而,從右邊看的視圖不容易得到。

//方法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; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 北海市| 余干县| 漠河县| 微山县| 阜南县| 仁寿县| 和顺县| 页游| 滁州市| 阳东县| 潞西市| 甘谷县| 罗平县| 综艺| 依兰县| 崇义县| 绵竹市| 商水县| 嘉义县| 中超| 延津县| 星子县| 高雄市| 南康市| 莱芜市| 赣州市| 平山县| 壤塘县| 会理县| 会同县| 西乌| 晋州市| 炉霍县| 民乐县| 固阳县| 房山区| 如东县| 荃湾区| 舟山市| 当雄县| 肥西县|