leetcode_树_543. The diameter of the binary tree (#)

Hello, everyone, I am a pig who is dominated by cabbage.

A person who loves to study, sleepless and forgets to eat, is obsessed with the girl's chic, calm and indifferent coding handsome boy.

1. Subject content

Given a binary tree, you need to calculate its diameter and length. The diameter length of a binary tree is the maximum of the path lengths of any two nodes. This path may or may not pass through the root node.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
returns 3, and its length is the path [4,2,1,3] or [5,2,1,3].
Note: The length of the path between two nodes is expressed by the number of edges between them.

Two, problem-solving ideas

Still using our framework thinking, there is really no nonsense in the title. What needs to be noted here is the sentence "This path may or may not pass through the root node". There may be a root node that does not pass. It may be longer than the path through the root node.

Three, code implementation

class Solution {
    
    
    private int max;
    public int diameterOfBinaryTree(TreeNode root) {
    
    
        if(root == null) return 0;
        getHeight(root);
        return max;
    }

    public int getHeight(TreeNode root) {
    
    
        if(root == null) return 0;
        int left = getHeight(root.left);
        int right = getHeight(root.right);
        int height =  Math.max(left,right)+1;
        max = Math.max(left + right ,max);
        return height;
    }

}

I'm so lazy lately. I haven't read the questions for a few days. I really learned from morning to night on Saturday and Sunday. I'm so tired, I really have to vomit. Come on! In the future, I will be grateful to myself desperately, saying so, but when I hear desperately, it means going to the battlefield. It is heroic, but learning is really a monotonous and boring process.

Guess you like

Origin blog.csdn.net/weixin_44226263/article/details/109438025