Last active
November 30, 2024 15:35
-
-
Save ghadj/03181838e1700e62c252cc11a2810d01 to your computer and use it in GitHub Desktop.
Leetcode #199
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * --- | |
| * [https://leetcode.com/problems/binary-tree-right-side-view] | |
| * 199. Binary Tree Right Side View | |
| * Given the root of 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. | |
| * --- | |
| */ | |
| class SolutionBFS { | |
| public List<Integer> rightSideView(TreeNode root) { | |
| if (root == null) | |
| return Collections.emptyList(); | |
| List<Integer> result = new ArrayList<>(); | |
| Queue<Pair<Integer, TreeNode>> queue = new LinkedList<>(); | |
| queue.add(new Pair<>(0, root)); | |
| while (!queue.isEmpty()) { | |
| Pair<Integer, TreeNode> node = queue.remove(); | |
| Integer depth = node.getKey(); | |
| TreeNode treeNode = node.getValue(); | |
| if (result.size() <= depth) | |
| result.add(treeNode.val); | |
| if (treeNode.right != null) | |
| queue.add(new Pair(depth + 1, treeNode.right)); | |
| if (treeNode.left != null) | |
| queue.add(new Pair(depth + 1, treeNode.left)); | |
| } | |
| return result; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * --- | |
| * [https://leetcode.com/problems/binary-tree-right-side-view] | |
| * 199. Binary Tree Right Side View | |
| * Given the root of 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. | |
| * --- | |
| */ | |
| class SolutionDFS { | |
| public List<Integer> rightSideView(TreeNode root) { | |
| List<Integer> result = new ArrayList<>(); | |
| dfs(root, 0, result); | |
| return result; | |
| } | |
| private void dfs(TreeNode node, int depth, List<Integer> result) { | |
| if (node == null) | |
| return; | |
| if (depth == result.size()) | |
| result.add(node.val); | |
| dfs(node.right, depth + 1, result); | |
| dfs(node.left, depth + 1, result); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment