Halo World

[LeetCode] 543. Diameter of Binary Tree 본문

스터디/알고리즘 문제풀이

[LeetCode] 543. Diameter of Binary Tree

_Yeony 2021. 9. 30. 08:31

https://leetcode.com/problems/diameter-of-binary-tree/

class Solution {
    int max=0;
    public int diameterOfBinaryTree(TreeNode root) {
        int left = findDepth(root.left);
        int right = findDepth(root.right);
        return Math.max(left + right, max);
    }
    
    int findDepth(TreeNode node) {
        if(node==null)    return 0;
        int left = findDepth(node.left);
        int right = findDepth(node.right);
        max = Math.max(left + right, max);
        return Math.max(left, right)+1;
    }
}

 

> 시간 복잡도 : O(n)

> 공간 복잡도 : O(n)