반응형
199. Binary Tree Right Side View
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제가 영어로 돼있어서 이상하게 문제를 풀다가 시간을 엄청 낭비했다.
가장 오른쪽 노드들만 모아서 보여주라는게 아니라 왼쪽노드든 오른쪽노드든 오른쪽에서 봤을때 보이는 노드들을 배열로 리턴하라는것이였다. 결국 왼쪽트리도 검색해야한다는것
노드 컨트롤하는 방법을 따로 정리했으나 아직도 익숙하지 않다.
자주 보고 계속 다시풀어보고 주석 읽어야겠다.
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var rightSideView = function (root) {
let result = [];
function dfs(node, level) {//dfs 펑션 하나 만들고 level은 result에 추가할때마다 +1씩올릴것임
if (!node) return; //노드가 없으면 그냥 리턴
if (result.length === level) { // 새로운 레벨에 처음 도달했을 때 오른쪽 값 추가
result.push(node.val);//result에 node.val을 넣기
}
// 오른쪽 자식부터 탐색하기때문에 새로운 레밸 도착시 오른쪽 값만 들어가는것임
dfs(node.right, level + 1);
// 왼쪽 자식 탐색 오른쪽 부터 탐색했으니 오른쪽 없을때 그 아래레벨 값부터 추가됨
dfs(node.left, level + 1);
}
dfs(root, 0);// dfs 돌리기 시작
return result;
};
반응형
'코딩테스트' 카테고리의 다른 글
217. Contains Duplicate (0) | 2024.02.19 |
---|---|
338. Counting Bits (0) | 2024.02.19 |
287. Find the Duplicate Number (2) | 2024.02.13 |
121. Best Time to Buy and Sell Stock (1) | 2024.02.13 |
125. Valid Palindrome (1) | 2024.02.13 |