fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. struct TreeNode{
  4. int val;
  5. TreeNode*right;
  6. TreeNode*left;
  7. TreeNode(int val):left(nullptr),right(nullptr),val(val){};
  8. };
  9. int height(TreeNode* root){
  10. if(root == nullptr)return 0;
  11. return 1+ max(height(root->right),height(root->left));
  12. }
  13. int diameter(TreeNode*root){
  14. if(root == nullptr)return 0;
  15.  
  16. int l = height(root->left);
  17. int r = height(root->right);
  18.  
  19. int ld = diameter(root->left);
  20. int rd = diameter(root->right);
  21.  
  22. return max(l+r,max(ld,rd));
  23. }
  24. TreeNode* buildTree(){
  25. int x;cin>>x;
  26. if(x==-1)return nullptr;
  27. TreeNode* root = new TreeNode(x);
  28.  
  29. queue<TreeNode*>q;
  30. q.push(root);
  31.  
  32. while(!q.empty()){
  33. auto u = q.front();
  34. q.pop();
  35.  
  36. if(cin>>x && x!=-1){
  37. u->left = new TreeNode(x);
  38. q.push(u->left);
  39. }
  40. if(cin>>x && x!=-1){
  41. u->right = new TreeNode(x);
  42. q.push(u->right);
  43. }
  44. }
  45. return root;
  46. }
  47. int main() {
  48. TreeNode* root = buildTree();
  49. cout<<diameter(root);
  50. return 0;
  51. }
Success #stdin #stdout 0.01s 5284KB
stdin
1 3 -1 5 7 6 -1 -1 4
stdout
4