1. 문제 및 예시

 

Given a binary tree, you need to compute 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 may or may not pass through the root.

 

 

Example:
Given a binary tree


Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

 

** The length of path between two nodes is represented by the number of edges between them.

 

 

 

2. 풀이

 

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var diameterOfBinaryTree = function(root) {
    if(!root) return 0;
    let result = -1;
    let getH = function (node, h) {
        if(!node) return 0;
        let lh = getH(node.left);
        let rh = getH(node.right);
        result= Math.max(result, 1 + lh + rh);
        return 1 + Math.max(lh, rh);
    }
    getH(root);
    return result -1;
};

** 좌측 노드의 최대 깊이와 우측 노드의 최대 깊이를 구해 더한다.

 

 

3. 결과

 


106 / 106 test cases passed.
Status: Accepted
Runtime: 84 ms
Memory Usage: 37.4 MB

 

 

 

반응형

+ Recent posts