미리수얌 블로그

Leetcode: Diameter of Binary Tree 본문

코딩문제풀이/Leetcode

Leetcode: Diameter of Binary Tree

미리수얌 2018. 9. 29. 15:06

Diameter of Binary Tree

Binary Tree 가 주어 졌을때 가장 긴 diameter 구하시오. 예: Binary Tree 가 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