其他分享
首页 > 其他分享> > 543求二叉树的直径

543求二叉树的直径

作者:互联网

 

 

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxres=0;
    int diameterOfBinaryTree(TreeNode* root) {
        int high=hight(root);
        return maxres;
    }
    int hight(TreeNode* root)
    {
        if(root==nullptr)
        {
            return 0;
        }
        int left_h=hight(root->left);
        int right_h=hight(root->right);
        //应该是在递归求以每个节点作为根时树的深度时的最大值 因为不一定就是以root为根时结果会最大
        maxres=max(maxres,left_h+right_h);
        return max(left_h,right_h)+1;
    }
};

 

TRANSLATE with x English
Arabic Hebrew Polish
Bulgarian Hindi Portuguese
Catalan Hmong Daw Romanian
Chinese Simplified Hungarian Russian
Chinese Traditional Indonesian Slovak
Czech Italian Slovenian
Danish Japanese Spanish
Dutch Klingon Swedish
English Korean Thai
Estonian Latvian Turkish
Finnish Lithuanian Ukrainian
French Malay Urdu
German Maltese Vietnamese
Greek Norwegian Welsh
Haitian Creole Persian  
  TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back

标签:right,TreeNode,int,nullptr,543,二叉树,直径,root,left
来源: https://www.cnblogs.com/libin123/p/15307443.html