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 may or may not pass through the root.

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

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

 

Diameter of Binary Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

이진트리의 left, right 노드의 가장 긴 길이를 구하는 문제이다.

가장 큰 경우의 수를 구해야한다. 문제를 잘못이해했다..ㅎ

int max = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        maxDiameter(root);
        return max;
    }
    
    private int maxDiameter(TreeNode root) {
        if(root==null) return 0;
        
        int leftCount = maxDiameter(root.left);
        int rightCount = maxDiameter(root.right);
        
        max = Math.max(max, leftCount+rightCount);
        
        return Math.max(leftCount, rightCount) +1;
        
    }

왼쪽노드와 오른쪽 노드를 더하면서 전역변수인 max와 비교한다. 이걸 재귀적으로 계속반복하여 답을 도출하는 것이다. 

참고 코드

'Algorithm > LeetCode' 카테고리의 다른 글

LeetCode 234. Palindrome Linked List  (0) 2022.06.28
LeetCode 206. Reverse Linked List  (0) 2022.06.28
LeetCode 338. Counting Bits  (0) 2022.06.25
LeetCode 155. Min Stack  (0) 2022.06.24
LeetCode 104. Maximum Depth of Binary Tree  (0) 2022.06.24

+ Recent posts