[LeetCode]Binary Tree Right Side View
2015-07-26 20:19
357 查看
解题思路:
宽度搜索,记录每一个node的height,当遇到当前node的height与前一个node的height不一样时,说明前一个node是那个height level的最右边的node,可以把val加入return vector
宽度搜索,记录每一个node的height,当遇到当前node的height与前一个node的height不一样时,说明前一个node是那个height level的最右边的node,可以把val加入return vector
/** * 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 {}; queue<TreeNode* > st; queue<int> stHeight; int preHeight = 0; TreeNode* preNode = root; vector<int> ret; st.push(root); stHeight.push(0); while(!st.empty()){ TreeNode* curNode = st.front(); st.pop(); int curHeight = stHeight.front(); stHeight.pop(); if (curNode != NULL){ if (curHeight != preHeight){ ret.push_back(preNode->val); } preNode = curNode; preHeight = curHeight; st.push(curNode->left); stHeight.push(curHeight+1); st.push(curNode->right); stHeight.push(curHeight+1); } } if (preNode != NULL){ ret.push_back(preNode->val); } return ret; } };
相关文章推荐
- 按键事件在java framework中的流程
- Head First设计模式悟道
- 常用的汉字,用于获得随机图片
- HDU 5310 Souvenir
- 找短板1:柱状图中的最大矩阵面积
- HDU 2222 Keywords Search(AC自动机)
- c语言 模拟 库函数 strstr()函数
- 埃氏筛法(快速筛选n以内素数的个数)
- UVA 299 Train Swapping
- hdu 5306 Gorgeous Sequence(暴力线段树)(好题)
- Loadrunner关于页面检查的几个函数详解
- tomcat启动成功外网无法访问
- 求二叉树中节点的最大距离
- 记录自己的傻逼的错误:找不到或无法加载主类
- Python项目9:文件共享2
- LightOJ1248-Dice (III)
- hdoj 1005Number Sequence
- Problem K 栈
- Android Gradle Plugin指南(三)----依赖关系,Android库和多项目设置
- UVA 152 Tree's a Crowd