199. Binary Tree Right Side View(BFS)
来源:互联网 发布:退火算法 matlab 编辑:程序博客网 时间:2024/06/06 18:53
1. Description
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].
2.Code
- 普通版
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<int> rightSideView(TreeNode* root) { if(root== NULL) return {}; vector<int> res; TreeNode* node = NULL; queue<TreeNode*> tmp; tmp.push(root); //res.push_back(root->val); while(!tmp.empty()) { res.push_back(tmp.back()->val); for(int i = 0, n = tmp.size(); i < n; i++) { node = tmp.front(); tmp.pop(); if(node->left != NULL) { tmp.push(node->left); } if(node->right != NULL) { tmp.push(node->right); } } } return res; }};
- 优化版
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxlevel = 0; vector<int> sln; vector<int> rightSideView(TreeNode* root) { if(!root) return sln; visit(root,1); return sln; } void visit(TreeNode* node, int level) { if(level > maxlevel) { sln.push_back(node->val); maxlevel = level; } if(node->right) visit(node->right, level + 1); if(node->left) visit(node->left, level + 1); }};
阅读全文
0 0
- [BFS]199. Binary Tree Right Side View
- 199. Binary Tree Right Side View(BFS)
- Tree-----199. Binary Tree Right Side View
- [LeetCode]199.Binary Tree Right Side View
- LeetCode 199. Binary Tree Right Side View
- [leetcode] 199.Binary Tree Right Side View
- [leetcode] 199. Binary Tree Right Side View
- [LeetCode]199. Binary Tree Right Side View
- 199. Binary Tree Right Side View LeetCode
- leetcode 199. Binary Tree Right Side View
- [LeetCode]199. Binary Tree Right Side View
- [LeetCode]199. Binary Tree Right Side View
- 199. Binary Tree Right Side View
- [LeetCode] 199. Binary Tree Right Side View
- LeetCode *** 199. Binary Tree Right Side View
- LeetCode 199. Binary Tree Right Side View
- 199. Binary Tree Right Side View
- 199. Binary Tree Right Side View
- 安装vue项目启动报错Cannot find module
- 数电实验,如何安装Quartus II软件?
- Ubuntu下查看Android APK 别名
- 一鼓作气(朝鲜歌曲)
- bzoj 1725:Corn Fields牧场的安排
- 199. Binary Tree Right Side View(BFS)
- gcc xx.c:(.text+0x11): undefined reference to `sqrt'
- Java(3-3)
- UVa 123|Searching Quickly|字符串处理
- 个人计划《2017-10-06》
- HYSBZ1941-Hide and Seek
- shell脚本语法
- 先码一个,try catch没有捕获到OutOFBoundsException
- DBSDFZOJ 模拟考试 命运 最小生成树+乱搞