본문 바로가기
Programming/Algorithm

[leetcode] DiameterofBinaryTree

by 읽고 쓰는 개발자 2020. 11. 29.

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

import exam.TreeNode;

public class DiameterofBinaryTree {
    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode(4);
        TreeNode treeNode2 = new TreeNode(5);
        TreeNode treeNode3 = new TreeNode(2, treeNode1, treeNode2);
        TreeNode treeNode4 = new TreeNode(3);
        TreeNode treeNode = new TreeNode(1, treeNode3, treeNode4);


        System.out.println(diameterOfBinaryTree(treeNode));
    }


    static int answer;
    public static int diameterOfBinaryTree(TreeNode root) {

        if(root == null) return 0;
        answer = 0;
        diameterOfBinaryTreeDFS(root);
        return answer;
    }

    private static int diameterOfBinaryTreeDFS(TreeNode root) {
        if(root.left == null && root.right == null) return 1;
        int leftVal = root.left == null ? 0 : diameterOfBinaryTreeDFS(root.left);
        int rightVal = root.right == null ? 0 : diameterOfBinaryTreeDFS(root.right);
        answer = Math.max(leftVal + rightVal , answer);

        return Math.max(leftVal + 1, rightVal + 1);
    }
}

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

[leetcode] LongestIncreasingSubsequence  (0) 2020.11.29
[leetcode] GameofLife  (0) 2020.11.29
[leetcode] CourseSchedule  (0) 2020.11.29
[leetcode] CombinationSum  (0) 2020.11.29
[leetcode] WordSearchII  (0) 2020.11.29