[Leetcode] The diameter of the leetcode543 binary tree: question ideas and codes

1. Title description

Portal: Leetcode 543
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
/ \
45
returns 3, which is the path length [4,2,1,3] or [5,2,1,3].

2. Thinking

This topic is actually not difficult, it is also an easy difficult topic, but I am not particularly familiar with the topic of trees. Although many times I know that it is a recursive method, I still don't know how to design the recursive process.
This question is actually a simple recursive question. The recursive function depth returns the depth of the current node each time, but the depth here is not what we usually say, the length from the root node to each node, but a depth value calculated from bottom to top. This is what I didn't think clearly when I first wrote it myself, because I usually use dfs from top to bottom to calculate the depth. But in fact, it is the same from bottom to top. Just pay attention to the recursive exit. When p=NULL, the exit returns 0, and the depth at this time is 0. When calculating the depth corresponding to each node, it should be max(left,right)+1, this is also understandable, because we have to get a maximum depth every time, and then get the maximum diameter length.
So this topic is actually a topic for calculating depth, but the depth here is not the same as our traditional depth.

3. Passed code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    int max_ans=0;
    int diameterOfBinaryTree(TreeNode* root) {
    
    
        depth(root);
        return max_ans;
    }
    int depth(TreeNode*p)
    {
    
    
        if(p==NULL)
        return 0;
        int left=depth(p->left);//得到left结点的深度
        int right=depth(p->right);//得到right结点的深度
        max_ans=max(max_ans,left+right);//计算当前长度,并且得到最大长度
        return max(left,right)+1;//返回当前结点的深度
    }
};

Guess you like

Origin blog.csdn.net/qq_38391210/article/details/108286578