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

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

Leetcode 199. Binary Tree Right Side View

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

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; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 金堂县| 登封市| 灯塔市| 宜君县| 淮安市| 商洛市| 通辽市| 滨海县| 察哈| 东源县| 阜南县| 花莲市| 呼伦贝尔市| 静安区| 咸宁市| 赣榆县| 丰台区| 安塞县| 凤冈县| 石棉县| 汤原县| 略阳县| 杭州市| 彝良县| 乌拉特后旗| 永兴县| 曲水县| 绥滨县| 长汀县| 老河口市| 河北区| 奇台县| 汽车| 瓮安县| 张家港市| 大洼县| 翁牛特旗| 饶平县| 涿鹿县| 新民市| 定南县|