199. Binary Tree Right Side View
来源:互联网 发布:淘宝上的天王表是正品 编辑:程序博客网 时间:2024/06/03 12:00
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]
.
题目要求返回从右往左看一颗二叉树能看到的数,用BSF的方法,取每一层的队列的队尾元素组成答案。
代码:
class Solution {public: vector<int> rightSideView(TreeNode* root) { vector<int>res; if(!root) return res; queue<TreeNode *>q; q.push(root); while(!q.empty()) { res.push_back(q.back()->val); int n=q.size(); for(int i=0;i<n;i++) { TreeNode *cur=q.front(); q.pop(); if(cur->left) q.push(cur->left); if(cur->right) q.push(cur->right); } } return res; }};
还可以直接遍历二叉树(优先右子树),每一层肯定能看到一个数,所以如果res的元素个数比层数小就往res后添加当前节点的值。
代码:
class Solution {public: void recursion(TreeNode *root, int level, vector<int> &res) { if(root==NULL) return ; if(res.size()<level) res.push_back(root->val); recursion(root->right, level+1, res); recursion(root->left, level+1, res); } vector<int> rightSideView(TreeNode *root) { vector<int> res; recursion(root, 1, res); return res; }};
0 0
- 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
- 199. Binary Tree Right Side View
- 199. Binary Tree Right Side View
- OSC源码学习随笔.2
- vim配置文件
- 文章标题
- memcache PHP扩展安装配置
- 内建模块-collections
- 199. Binary Tree Right Side View
- tabbar颜色修改
- PHP绑定手机
- 设计模式六大原则
- Thinkphp5 学习笔记之视图
- 运行React-Rative示例工程MyProject报错
- db2查看修改端口号
- overridePendingTransition的简介
- 将MongoDB安装为Windows服务时cmd命令下路径中存在空格的问题