二刷 07/2022
Version #1 DFS
感觉没有一刷做的好
这里是先看左边然后如果右边遇到了新的就覆盖之前的
一刷是直接从右往左看,取代了覆盖的过程
Time O(N)
Space O(N)
Runtime: 1 ms, faster than 95.06% of Java online submissions for Binary Tree Right Side View.
Memory Usage: 40.8 MB, less than 93.77% of Java online submissions for Binary Tree Right Side View.
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
dfs(root, result, 0);
return result;
}
private void dfs(TreeNode node, List<Integer> result, int level) {
if (node == null) {
return;
}
if (level == result.size()) {
result.add(node.val);
} else {
result.set(level, node.val);
}
dfs(node.left, result, level + 1);
dfs(node.right, result, level + 1);
}
}
一刷
一刷
//
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root != null) {
helper(root, result, 0);
}
return result;
}
private void helper(TreeNode node, List<Integer> result, int level) {
if (level >= result.size()) {
result.add(node.val);
}
if (node.right != null) {
helper(node.right, result, level + 1);
}
if (node.left != null) {
helper(node.left, result, level + 1);
}
}
}
No comments:
Post a Comment