[LeetCode#687] Longest Univalue Path

2024. 9. 21. 20:43·Algorithm/문제풀이

❒ Description


날짜 2024.09.21 (토)
레벨 Medium
제목 Longest Univalue Path
링크 https://leetcode.com/problems/longest-univalue-path/submissions/1397321235/
자료구조 트리
알고리즘 X
시간 복잡도 O(n)

 

543. Diameter of Binary Tree와 굉장히 유사한 문제이다.

 

 

 

 

 

❒ 문제 분석


부모-노드의 value와 자식-노드의 value가 동등한지를 판단하여야 하는 문제이다. 

이 문제 또한 재귀를 통해 Left, Right 자식 트리의 깊이를 파악함과 동시에 가장 긴 경로를 파악해야 한다.

위 그림에서 리프노드의 1과 1은 부모노드의 값인 4와 동일하지 못하기 때문에 문제의 요구사항에 충족하지 못한다.

 

 

 

 

 

❒ Solution


public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    public boolean isEqual(TreeNode node) {
        return node != null && val == node.val;
    }
}
int maxLenght = 0;
public int longestUnivaluePath(TreeNode root) {
    depth(root);
    return maxLength;
}

private int depth(TreeNode node) {
    int leftDepth = depth(node.left);
    int rightDepth = depth(node.right);
    
    // 부모노드의 val과 자식노드의 val이 동일한지 validation
    if (node.isEqual(node.left)) {
        leftDepth ++;
    } else {
        leftDepth = 0;
    }
    if (node.isEqual(node.right)) {
        rightDepth ++;
    } else {
        rightDepth = 0;
    }
    maxLength = Math.max(maxLength, leftDepth + rightDepth);
    return Math.max(leftDepth, rightDepth);
}

값이 동일한지 확인하는 로직은 TreeNode가 책임져야 하는 역할이기에 TreeNode에 isEqual 메소드를

작성하였다. 하지만 LeetCode에서는 해당 메소드를 알수 없기 때문에 통과되지 않는다.

 

 

 

 

 


'Algorithm > 문제풀이' 카테고리의 다른 글

[LeetCode#110] Balanced Binary Tree  (0) 2024.09.23
[LeetCode#] Invert Binary Tree  (0) 2024.09.22
[LeetCode#455] Assign Cookies  (0) 2024.09.19
[LeetCode#134] Gas Station  (0) 2024.09.18
[LeetCode#621] Task Scheduler  (0) 2024.09.17
'Algorithm/문제풀이' 카테고리의 다른 글
  • [LeetCode#110] Balanced Binary Tree
  • [LeetCode#] Invert Binary Tree
  • [LeetCode#455] Assign Cookies
  • [LeetCode#134] Gas Station
gilbert9172
gilbert9172
gilbert9172 님의 블로그 입니다.
  • gilbert9172
    バックエンド
    gilbert9172
  • 전체
    오늘
    어제
    • All Categories (174)
      • 우테코 7기 (21)
        • 1주차 (8)
        • 2주차 (5)
        • 3주차 (6)
      • Langauge (4)
        • Java (3)
        • Kotlin (1)
      • Back-End (13)
        • SpringBoot (1)
        • Trouble Shooting (0)
        • Setup & Configuration (1)
        • SQL (3)
        • Redis (8)
      • Architecture (6)
        • Multi Module (1)
        • DDD (5)
      • CS (30)
        • Data Structure (6)
        • Operating System (0)
        • Network (12)
        • Database (10)
        • Design Pattern (2)
      • Algorithm (78)
        • 내용 정리 (18)
        • 문제풀이 (60)
      • DevOps (6)
        • AWS (5)
        • Git (1)
      • Front-End (1)
        • Trouble Shooting (1)
      • Project (6)
        • 페이스콕 (6)
      • Book (8)
        • 이벤트 기반 마이크로서비스 구축 (6)
        • 친절한 SQL 튜닝 (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    binarysearch
    Two-Pointer
    오블완
    부분단조성
    sliding-window
    Back-Tracking
    greedy
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
gilbert9172
[LeetCode#687] Longest Univalue Path
상단으로

티스토리툴바