LeetCode543 Diameter of binary tree

the defination of diameter of binary tree is the longest path(the edge number instead of the nodes number) between any two nodes in a tree.
在这里插入图片描述

idea:
this is the kind of problem that I have no single clue

class Solution {
    int maxLevel = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        
        deepest(root);
        return maxLevel;
    }
    
    private int deepest(TreeNode root) { //this function means deepest of this tree
        
        if (root == null) {
            return 0;//level 0
        }
        
        int left = deepest(root.left); //the deepest of left subtree
        int right = deepest(root.right); //the deepest of right subtree
        
        maxLevel = Math.max(maxLevel, left +  right); //update maxLevel, we always want a global max depth
        
        return Math.max(left, right) + 1; //this is the depth with root is current root
    }
}
posted @ 2020-11-04 09:19  EvanMeetTheWorld  阅读(19)  评论(0)    收藏  举报