Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- Bit
- LinkedList
- 공채
- traversal
- 배열
- Bubble Sort
- binary search tree
- sorting
- stack
- Easy
- 2019 카카오
- 정렬
- tree
- 스택
- 카카오
- Medium
- Subset
- leetcode
- 리스트
- kakao
- list
- 순회
- 트리
- Linked List
- 오픈 채팅방
- 완전검색
- Math
- bst
Archives
- Today
- Total
미리수얌 블로그
Leetcode: Diameter of Binary Tree 본문
Diameter of Binary Tree
Binary Tree 가 주어 졌을때 가장 긴 diameter 구하시오.
예: Binary Tree 가
출처 wikipedia
주어졌다면 [11, 6, 7, 2, 5, 9, 4] 나 [5, 6, 7, 2, 5, 9, 4] 둘다 제일큰 diameter 6 을 가지고 있습니다. 따라서 답은 6입니다.
이 문제는 depth 를 구하는 식으로 구할 수 있습니다. 7 을 보죠 7의 왼쪽 depth은 1 오른쪽 depth은 2임을 알 수 있습니다. 그럼 7의 최대 diameter 는 1 + 2 = 3 이 될것입니다.
private int maxDia;
public int diameterOfBinaryTree(TreeNode root) {
depth(root);
return maxDia;
}
private int depth(TreeNode node) {
if (node == null) return 0;
int leftDepth = depth(node.left);
int rightDepth = diameter(node.right);
maxDia = Math.max(depth+ rightDepth, maxDia);
return Math.max(leftDepth, rightDepth) + 1;
}
'코딩문제풀이 > Leetcode' 카테고리의 다른 글
Leetcode: Power of Two (0) | 2018.10.05 |
---|---|
Leetcode: Set Mismatch (0) | 2018.10.05 |
Leetcode: String Compression (0) | 2018.09.29 |
Leetcode: Assign Cookies (0) | 2018.09.29 |
LeetCode: Kth Smallest Element in a BST (0) | 2018.09.29 |
Comments