[LeetCode] - M - 199. Binary Tree Right Side View

2023. 9. 6. 16:21· 알고리즘/문제
목차
  1. 🔥 - Java 코드

https://leetcode.com/problems/binary-tree-right-side-view/description/?envType=study-plan-v2&envId=top-interview-150

 

Binary Tree Right Side View - LeetCode

Can you solve this real interview question? 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.   Example 1: [https://asse

leetcode.com

 

🌿 - 문제 설명

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.

간단하게 설명하면 tree의 depth에서 가장 오른쪽 값을 반환

 

📌 - 풀이

처음엔 rightNode들만 반환하면 되는 줄 알았는데, 각각의 depth에서 가장 오른쪽 노드를 찾는 문제였음

  1. 중위순회를 한다.
  2. 중위순회를 하면 왼쪽에서 오른쪽으로 진행하기 때문에, map을 이용해서 map의 키값을 depth로 놓으면 해당 depth에서 가장 오른쪽 노드만 계속해서 덮여쓰기 되므로 원하는 값을 찾을 수 있음

 

🔥 - Java 코드

 


  
/**
* 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 {
List<Integer> list = new ArrayList<>();
Map<Integer,Integer> map = new HashMap<>();
public List<Integer> rightSideView(TreeNode root) {
inorder(root,1);
for(int a : map.keySet()){
list.add(map.get(a));
}
return list;
}
public void inorder(TreeNode node,int depth){
if(node == null){
return;
}
inorder(node.left,depth +1);
map.put(depth,node.val);
inorder(node.right,depth +1);
}
}
  1. 🔥 - Java 코드
'알고리즘/문제' 카테고리의 다른 글
  • [LeetCode] - M - 133. Clone Graph
  • [LeetCode] - M - 211. Design Add and Search Words Data Structure
  • [LeetCode] - M - Kth Smallest Element in a BST
  • [LeetCode] - M - Search in Rotated Sorted Array
Casteira
Casteira
할 뿐
Casteira
SpongeCake
Casteira
전체
오늘
어제
  • __Main__ (104)
    • 알고리즘 (65)
      • 개념 (6)
      • 문제 (58)
    • 컴퓨터 구조 (9)
      • 자료 구조 (2)
      • OS (7)
    • 웹 (1)
      • 자바 (1)
      • 스프링 (5)
      • SQL (0)
    • 기록 (4)
      • 포트폴리오 (2)
    • 정글 (18)
      • TIL (17)

블로그 메뉴

  • 🗒️ 깃허브
  • 태그
  • 방명록
  • 관리

공지사항

인기 글

태그

  • dp
  • 크래프톤
  • java
  • 크래프톤 정글
  • 정글
  • spring
  • 백준 골드
  • annotation
  • 코딩테스트
  • springboot
  • framework
  • 백준

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.1
Casteira
[LeetCode] - M - 199. Binary Tree Right Side View
테마상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.