Problem: 199. 二叉树的右视图
文章目录
- 思路
- 💖 BFS
- 💖 DFS
思路
👩🏫 甜姨
💖 BFS
⏰ 时间复杂度: O ( n ) O(n) O(n)
🌎 空间复杂度: O ( n ) O(n) O(n)
class Solution {public List<Integer> rightSideView(TreeNode root) {List<Integer> res = new ArrayList<>();if (root == null) {return res;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {int size = queue.size();for (int i = 0; i < size; i++) {TreeNode node = queue.poll();if (node.left != null) {queue.offer(node.left);}if (node.right != null) {queue.offer(node.right);}if (i == size - 1) { //将当前层的最后一个节点放入结果列表res.add(node.val);}}}return res;}
}
💖 DFS
⏰ 时间复杂度: O ( n ) O(n) O(n)
🌎 空间复杂度: O ( n ) O(n) O(n)
/*** 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 {final List<Integer> ans = new ArrayList<>();public List<Integer> rightSideView(TreeNode root){dfs(root, 0);return ans;}private void dfs(TreeNode root, int d){if (root == null)return;if (d == ans.size())ans.add(root.val);dfs(root.right, d + 1);dfs(root.left, d + 1);}
}