[leetcode]48 Binary Tree Right Side View
来源:互联网 发布:for在c语言中的作用 编辑:程序博客网 时间:2024/05/01 18:06
题目链接:https://leetcode.com/problems/binary-tree-right-side-view/
Runtimes:9ms
1、问题
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、分析
说到底,就是求一棵树的右侧面照,即每一层从右往左第一个数字。肯定是分层遍历,但是这个过程有优化的地方,以前做类似分层遍历题目的时候都是多开几个大vector存储数据,现在又有了新的辨别方式,剩下了很多空间以及时间。
3、小结
只要记录一层最后访问的那个节点即可,即preh < h时,pret就是要求的最后节点。用队列会和遍历的顺序一样,选择正确的数据结构也是很重要的。
4、实现
/** * Definition for binary tree * 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) { queue <TreeNode *> tv; queue <int> iv; vector<int> rv; if(NULL == root) return rv; tv.push(root); iv.push(1); int preh = INT_MAX; TreeNode *pret; while(!tv.empty()) { TreeNode * t = tv.front(); tv.pop(); int h = iv.front(); iv.pop(); if(preh < h) rv.push_back(pret->val); if(NULL != t->left) { tv.push(t->left); iv.push(h + 1); } if(NULL != t->right) { tv.push(t->right); iv.push(h + 1); } preh = h; pret = t; } rv.push_back(pret->val); return rv; }};
5、反思
从编程之美吸收了很多优化方法,一本不错的书。
0 0
- [leetcode]48 Binary Tree Right Side View
- [leetcode][tree] Binary Tree Right Side View
- LeetCode OJ Binary Tree Right Side View
- LeetCode:Binary Tree Right Side View
- [leetcode] 199 Binary Tree Right Side View
- [LeetCode]199.Binary Tree Right Side View
- Leetcode: Binary Tree Right Side View
- LeetCode | Binary Tree Right Side View
- [LeetCode] Binary Tree Right Side View
- LeetCode: Binary Tree Right Side View
- [leetcode] Binary Tree Right Side View
- leetcode-199 Binary Tree Right Side View
- [LeetCode]Binary Tree Right Side View
- 199Binary Tree Right Side View-LeetCode
- Binary Tree Right Side View--LeetCode
- [LeetCode]Binary Tree Right Side View
- [LeetCode 199]Binary Tree Right Side View
- leetcode: Binary Tree Right Side View
- C++作业
- 第二章第二十二题
- Gray Code
- dbca建库报错exception in thread main
- selenium+java自动化测试框架之元素管理篇(yaml)
- [leetcode]48 Binary Tree Right Side View
- Android LayoutInflater原理分析,带你一步步深入了解View(一)
- 使用FileInputStream和FileOutputStream读写sdcard卡下的文件
- 黑马程序员——面向对象-多肽
- sqlserver 常见使用sql
- android ui布局之 merge include ViewStub
- C++小课堂--第一期---面向对象之前 --- 实现函数返回结构体,实现大数据的传输
- (android高仿系列)今日头条 --新闻阅读器 (一)
- Android 应用程序之间内容分享详解(一)