/** * 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 TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back