[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 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 <---
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 二叉树的右侧视图的更多相关文章
- [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 ...
- [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 ...
- [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 ...
- 199 Binary Tree Right Side View 二叉树的右视图
给定一棵二叉树,想象自己站在它的右侧,返回从顶部到底部看到的节点值.例如:给定以下二叉树, 1 <--- / \2 3 <--- \ ...
- leetcode 199 :Binary Tree Right Side View
// 我的代码 package Leetcode; /** * 199. Binary Tree Right Side View * address: https://leetcode.com/pro ...
- 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 这个题实际上就是把每一行最右侧的树打印出来,所以实际上还是一个层次遍历. 依旧利用之前层次遍历的代码,每次大的循环存 ...
- (二叉树 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 ...
- 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 ...
- 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 ...
随机推荐
- 正则爬取京东商品信息并打包成.exe可执行程序。
本文爬取内容,输入要搜索的关键字可自动爬取京东网站上相关商品的店铺名称,商品名称,价格,爬取100页(共100页) 代码如下: import requests import re # 请求头 head ...
- js中的全局对象
- CF622F——自然数幂和模板&&拉格朗日插值
题意 求 $ \displaystyle \sum_{i=1}^n i^k \ mod (1e9+7), n \leq 10^9, k \leq 10^6$. CF622F 分析 易知答案是一个 $k ...
- 4、NameNode启动过程详解
NameNode 内存 本地磁盘 fsimage edits 第一次启动HDFS 格式化HDFS,目的就是生成fsimage start NameNode,读取fsimage文件 start Data ...
- 14.go内置的rate包学习2(有花操作,必看)
package main import ( "fmt" "golang.org/x/time/rate" "time" ) func mai ...
- Tensorflow细节-Tensorboard可视化-简介
先搞点基础的 注意注意注意,这里虽然很基础,但是代码应注意: 1.从writer开始后边就错开了 2.writer后可以直接接writer.close,也就是说可以: writer = tf.summ ...
- javascript使用history api防止|阻止页面后退
奇葩需求啥时候都会有,最近有个需求是不允许浏览器回退,但是所有页面都是超链接跳转,于是乎脑壳没转弯就回答了做不到,结果尼玛被打脸了,这打脸的声音太响,终于静下心来看了下history api. 先上代 ...
- Java面试集合(三)-30道面试题
前言 大家好,我是 Vic,今天给大家带来Java面试集合(三)的概述,希望你们喜欢 三 1.在Java中是否可以含有多个类?答:可以含有多个类,但只有一个是public类,public类的类名与文件 ...
- (11)Go方法/接收者
方法和接收者 Go语言中的方法(Method)是一种作用于特定类型变量的函数.这种特定类型变量叫做接收者(Receiver).接收者的概念就类似于其他语言中的this或者 self. 方法的定义格式如 ...
- 梯度裁剪(Clipping Gradient):torch.nn.utils.clip_grad_norm
torch.nn.utils.clip_grad_norm_(parameters, max_norm, norm_type=2) 1.(引用:[深度学习]RNN中梯度消失的解决方案(LSTM) ) ...