上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
}
};
java 解法, 执行用时: 0 ms, 内存消耗: 41.1 MB, 提交时间: 2024-02-20 10:13:44
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private final List<Integer> ans = new ArrayList<>();
public List<Integer> rightSideView(TreeNode root) {
dfs(root, 0);
return ans;
}
private void dfs(TreeNode root, int depth) {
if (root == null) return;
if (depth == ans.size())
ans.add(root.val);
dfs(root.right, depth + 1);
dfs(root.left, depth + 1);
}
}
golang 解法, 执行用时: 0 ms, 内存消耗: 2.1 MB, 提交时间: 2024-02-20 10:13:25
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func rightSideView(root *TreeNode) (ans []int) {
var dfs func(*TreeNode, int)
dfs = func(node *TreeNode, depth int) {
if node == nil {
return
}
if depth == len(ans) {
ans = append(ans, node.Val)
}
dfs(node.Right, depth+1)
dfs(node.Left, depth+1)
}
dfs(root, 0)
return
}
python3 解法, 执行用时: 28 ms, 内存消耗: 16.4 MB, 提交时间: 2024-02-20 10:13:04
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
ans = []
def dfs(node: Optional[TreeNode], depth: int) -> None:
if node is None: return
if depth == len(ans):
ans.append(node.val)
dfs(node.right, depth + 1)
dfs(node.left, depth + 1)
dfs(root, 0)
return ans
python3 解法, 执行用时: 36 ms, 内存消耗: 15 MB, 提交时间: 2022-08-17 10:28:13
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# 我们对树进行深度优先搜索,在搜索过程中,我们总是先访问右子树。
# 那么对于每一层来说,我们在这层见到的第一个结点一定是最右边的结点。
# 这样一来,我们可以存储在每个深度访问的第一个结点,
# 一旦我们知道了树的层数,就可以得到最终的结果数组。
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
rightmost_value_at_depth = dict() # 深度为索引,存放节点的值
max_depth = -1
stack = [(root, 0)]
while stack:
node, depth = stack.pop()
if node is not None:
# 维护二叉树的最大深度
max_depth = max(max_depth, depth)
# 如果不存在对应深度的节点我们才插入
rightmost_value_at_depth.setdefault(depth, node.val)
stack.append((node.left, depth + 1))
stack.append((node.right, depth + 1))
return [rightmost_value_at_depth[depth] for depth in range(max_depth + 1)]