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.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation: 1 <---
/ \
2 3 <---
\ \
5 4 <---
 
给一个二叉树,想象你站在它的右边,返回你能看到的从上到下节点。实际上是二叉树层序遍历的一种变形,只需要保存每一层最右边的数字即可。
解法1:DFS
解法2:  BFS
 
Java: 
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
rightView(root, result, 0);
return result;
} public void rightView(TreeNode curr, List<Integer> result, int currDepth){
if(curr == null){
return;
}
if(currDepth == result.size()){
result.add(curr.val);
} rightView(curr.right, result, currDepth + 1);
rightView(curr.left, result, currDepth + 1); }
}  

Python: DFS 

# Time:  O(n)
# Space: O(h)
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None class Solution(object):
# @param root, a tree node
# @return a list of integers
def rightSideView(self, root):
result = []
self.rightSideViewDFS(root, 1, result)
return result def rightSideViewDFS(self, node, depth, result):
if not node:
return if depth > len(result):
result.append(node.val) self.rightSideViewDFS(node.right, depth+1, result)
self.rightSideViewDFS(node.left, depth+1, result)

Python: BFS  

# Time:  O(n)
# Space: O(n)
class Solution2(object):
# @param root, a tree node
# @return a list of integers
def rightSideView(self, root):
if root is None:
return [] result, current = [], [root]
while current:
next_level = []
for node in current:
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
result.append(node.val)
current = next_level return result

Python: Compute the right view of both right and left left subtree, then combine them. For very unbalanced trees, this can be O(n^2), though.

def rightSideView(self, root):
if not root:
return []
right = self.rightSideView(root.right)
left = self.rightSideView(root.left)
return [root.val] + right + left[len(right):]

Python: DFS-traverse the tree right-to-left, add values to the view whenever we first reach a new record depth. This is O(n).

def rightSideView(self, root):
def collect(node, depth):
if node:
if depth == len(view):
view.append(node.val)
collect(node.right, depth+1)
collect(node.left, depth+1)
view = []
collect(root, 0)
return view 

Python: Traverse the tree level by level and add the last value of each level to the view. This is O(n).

def rightSideView(self, root):
view = []
if root:
level = [root]
while level:
view += level[-1].val,
level = [kid for node in level for kid in (node.left, node.right) if kid]
return view  

C++: DFS

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;
}
};

C++: BFS 

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 size = q.size();
for (int i = 0; i < size; ++i) {
TreeNode *node = q.front();
q.pop();
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return res;
}
};

类似题目:

[LeetCode] 102. Binary Tree Level Order Traversal 二叉树层序遍历

[LeetCode] 107. Binary Tree Level Order Traversal II 二叉树层序遍历 II

All LeetCode Questions List 题目汇总

[LeetCode] 199. Binary Tree Right Side View 二叉树的右侧视图的更多相关文章

  1. [LeetCode] Binary Tree Right Side View 二叉树的右侧视图

    Given a binary tree, imagine yourself standing on the right side of it, return the values of the nod ...

  2. [leetcode]199. Binary Tree Right Side View二叉树右侧视角

    Given a binary tree, imagine yourself standing on the right side of it, return the values of the nod ...

  3. [leetcode]199. Binary Tree Right Side View二叉树右视图

    Given a binary tree, imagine yourself standing on the right side of it, return the values of the nod ...

  4. 199 Binary Tree Right Side View 二叉树的右视图

    给定一棵二叉树,想象自己站在它的右侧,返回从顶部到底部看到的节点值.例如:给定以下二叉树,   1            <--- /   \2     3         <--- \  ...

  5. leetcode 199 :Binary Tree Right Side View

    // 我的代码 package Leetcode; /** * 199. Binary Tree Right Side View * address: https://leetcode.com/pro ...

  6. leetcode 199. Binary Tree Right Side View 、leetcode 116. Populating Next Right Pointers in Each Node 、117. Populating Next Right Pointers in Each Node II

    leetcode 199. Binary Tree Right Side View 这个题实际上就是把每一行最右侧的树打印出来,所以实际上还是一个层次遍历. 依旧利用之前层次遍历的代码,每次大的循环存 ...

  7. (二叉树 bfs) leetcode 199. Binary Tree Right Side View

    Given a binary tree, imagine yourself standing on the right side of it, return the values of the nod ...

  8. leetcode@ [199] Binary Tree Right Side View (DFS/BFS)

    https://leetcode.com/problems/binary-tree-right-side-view/ Given a binary tree, imagine yourself sta ...

  9. Java for LeetCode 199 Binary Tree Right Side View

    Given a binary tree, imagine yourself standing on the right side of it, return the values of the nod ...

随机推荐

  1. jmeter+nmon+crontab简单的执行接口定时压测

    一.概述 临时接到任务要对系统的接口进行压测,上面的要求就是:压测,并发2000 在不熟悉系统的情况下,按目前的需求,需要做的步骤: 需要有接口脚本 需要能监控系统性能 需要能定时执行脚本 二.观察 ...

  2. Vuex 是什么?

    Vuex 是什么? Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件状态,并以相应的规则保证状态以一种可预测的方式发生变   什么是"状态管 ...

  3. xshell连接不上阿里云服务器Could not connect to 'ip' (port 22): Connection failed.解决过程

    记一次xshell阿里云服务器突然连接不上的解决办法: 1, 确认阿里云服务器安全组出入都有22,百度出来都说的这个和ip拦截设置,以防万一都设置了:但楼主设置后,还是连不上服务器: 只好下一步 2, ...

  4. 2019-2020-1 20199302《Linux内核原理与分析》第十一周作业

    缓冲区溢出 缓冲区溢出是指程序试图向缓冲区写入超出预分配固定长度数据的情况.这一漏洞可以被恶意用户利用来改变程序的流控制,甚至执行代码的任意片段.这一漏洞的出现是由于数据缓冲器和返回地址的暂时关闭,溢 ...

  5. 【洛谷P4585】 [FJOI2015]火星商店问题 线段树分治+可持久化trie

    感觉这个线段树分治和整体二分几乎相同啊~ code: #include <bits/stdc++.h> #define MAX 100300 #define ll long long #d ...

  6. Python爬虫 | Beautifulsoup解析html页面

    引入 大多数情况下的需求,我们都会指定去使用聚焦爬虫,也就是爬取页面中指定部分的数据值,而不是整个页面的数据.因此,在聚焦爬虫中使用数据解析.所以,我们的数据爬取的流程为: 指定url 基于reque ...

  7. 过滤器的API

    1.API a.生命周期(和servletcontext相似): (1)创建:服务器启动的时候创建(执行init方法). (2)销毁:服务器关闭的时候销毁(执行destory方法). b.filter ...

  8. I Count Two Three(打表+排序+二分查找)

    I Count Two Three 二分查找用lower_bound 这道题用cin,cout会超时... AC代码: /* */ # include <iostream> # inclu ...

  9. 转载:Databricks孟祥瑞:ALS 在 Spark MLlib 中的实现

    Databricks孟祥瑞:ALS 在 Spark MLlib 中的实现 发表于2015-05-07 21:58| 10255次阅读| 来源<程序员>电子刊| 9 条评论| 作者孟祥瑞 大 ...

  10. Django自带后台admin的使用配置

    Django自带后台使用配置参考官网地址:https://docs.djangoproject.com/en/1.11/ref/contrib/admin/ ,本文章值是介绍简单配置,如果需要详细内容 ...