LeetCode finds binary tree diameter

Title description

Insert picture description here

Topic analysis

The so-called diameter is to find the sum of the depths of the left and right subtrees, and this problem cannot only consider the sum of the depths of the left and right subtrees, because the root node can be omitted when the diameter is calculated. This means that if the right subtree of the root node has only one layer, but the left subtree is full of nodes, it is wrong to directly find the sum of the depths of the two subtrees of the root node.

The following is a more violent method I think: first traverse the binary tree, save all the internal nodes in an array (because the diameter of the leaf node is 0), then find the diameter of each node and return the maximum value.

class Solution {
    
    
public:
    vector<TreeNode*> nodes;

    int getDepth(TreeNode* root){
    
    
        if(root == NULL) return 0;
        int l_depth = getDepth(root->left);
        int r_depth = getDepth(root->right);
        return l_depth > r_depth ? l_depth+1 : r_depth+1;
    }

    void Traverse(TreeNode* root){
    
    
        if(root == NULL) return ;
        Traverse(root->left);
        if(root->left || root->right) nodes.push_back(root);//不要叶子结点
        Traverse(root->right);
    }


    int diameterOfBinaryTree(TreeNode* root) {
    
    
        if(root == NULL) return 0;
        if(root->left == NULL && root->right == NULL) return 0;//只有root结点
        Traverse(root);
        int res = INT_MIN;
        for(TreeNode* node : nodes){
    
    
            int cur_depth =  getDepth(node->left) + getDepth(node->right);
            res = res > cur_depth ? res : cur_depth;
        }
        return res;
    }
};

Insert picture description here
Of course, the efficiency is not high and it takes up extra space. The following is written after looking at the solution

  • When traversing, you can calculate the diameter and save it with global variables
  • Finally return to the global variable
class Solution {
    
    
public:
    int diameter = 0;

    int countDiameter(TreeNode* root){
    
    
        if(root == NULL) return 0;
        int l_depth = countDiameter(root->left);
        int r_depth = countDiameter(root->right);
        diameter = max(diameter , l_depth + r_depth);
        return max(l_depth , r_depth) + 1;
    }
    
    int diameterOfBinaryTree(TreeNode* root) {
    
    
        countDiameter(root);
        return diameter;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42500831/article/details/105241221