PS/LeetCode

LeetCode / Tree / 543번 / Diameter of Binary Tree / JS

KimMinJun 2023. 4. 28. 17:36

< 문제 바로가기 >

 

Diameter of Binary Tree - LeetCode

Can you solve this real interview question? Diameter of Binary Tree - Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path

leetcode.com

 

< 문제 간단설명 >

diameter를 직역하면 지름이라는 뜻인데... 이 문제에서 지름을 반환하면 된다(?).

문제에서 나타내는 diameter란 트리내에서 임의로 어떤 노드 두개를 선택했을 때의 그 사이가 가장 긴 거리를 나타낸다.

위와 같은 트리가 주어졌을 때, 여기서의 diameter는 4(or 5) -> 2 -> 1 -> 3을 나타낸다. 혹은 거꾸로도 가능하다.

 

/**
 * 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 diameterOfBinaryTree = function(root) {
    let max = 0;

    const DFS = (node) => {
        if(node === null) {
            return 0;
        }

        let left = DFS(node.left);
        let right = DFS(node.right);

        // 왼쪽 subtree와 오른쪽 subtree중 더 depth가 큰 것
        max = Math.max(max, left + right);
        return Math.max(left, right) + 1;
    }

    DFS(root);

    return max;
};