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. 使用SecureCRT操作linux系统时候的简单设置

    因为第一次访问一台虚拟机的时候会出现这样的情况;   底色为白色和乱码的情况 需要在选项----->会话选项中进行一些设置 用来解决乱码问题的这个设置为:

  2. iptables 通用语句

    iptables -t filter -nvL --line-number | grep destination -t :  指定表 {fillter|nat|mangle|raw} -v : 显示详 ...

  3. Linux中在vim/vi模式下对文本的查找和替换

    查找: 1.vim  filename  进入一般模式下 2.查找和替换方法 /word    向下查找word 的字符串  例如  /chengtingting   向下查找字符chengtingt ...

  4. SparkSQL-通过JDBC读写mysql数据库

    object JdbcDatasourceTest { def main(args: Array[String]): Unit = { val spark = SparkSession .builde ...

  5. [Dynamic Programming] 198. House Robber

    You are a professional robber planning to rob houses along a street. Each house has a certain amount ...

  6. WinDbg常用命令系列---单步执行p*

    p (Step) p命令执行单个指令或源代码行,并可选地显示所有寄存器和标志的结果值.当子例程调用或中断发生时,它们被视为单个步骤. 用户模式: [~Thread] p[r] [= StartAddr ...

  7. swiper轮播图插件

    一.简介 ①Swiper是纯javascript打造的滑动特效插件,面向手机.平板电脑等移动终端.Swiper能实现触屏焦点图.触屏Tab切换.触屏多图切换等常用效果. ②Swiper 是一款免费以及 ...

  8. JMeter学习1

    Jmeter的组织方式相对比较扁平,直接是TestPlan(相当于Project),TestPlan下创建的ThreadsGroup(相当于TestCase), Jmeter一个TestPlan也是一 ...

  9. HDU 1542.Atlantis-线段树求矩形面积并(离散化、扫描线/线段树)-贴模板

    好久没写过博客了,这学期不是很有热情去写博客,写过的题也懒得写题解.现在来水一水博客,写一下若干年前的题目的题解. Atlantis Time Limit: 2000/1000 MS (Java/Ot ...

  10. php在Linux下的相对路径问题

    如图所示,我在 /root/phpcode/ 下面有两个php文件. a.php 与 b.php,我用 a.php 去 require b.php ,然后 b.php 输出 1. 现在我在 /root ...