knakul853

Untitled

Jul 22nd, 2020
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. /**
  2. knakul853
  3.  */
  4. class Solution {
  5. public:
  6.     int diameterOfBinaryTree(TreeNode* root) {
  7.        
  8.         return dfs(root).first;
  9.        
  10.     }
  11.    
  12.     // max of {left+right, lft, right}  {di, hight};
  13.    
  14.   pair<int,int>  dfs(TreeNode* root)
  15.     {
  16.           if(!root)return{0,0};
  17.          
  18.           auto p1 = dfs(root->left);
  19.           auto p2 = dfs(root->right);
  20.          
  21.          int dim = max({p1.first, p2.first, p1.second + p2.second});
  22.      
  23.       return {dim, max(p1.second, p2.second)+1};
  24.      
  25.     }
  26. };
  27.  
  28. class Solution {
  29. public:
  30.     int mx = 0;
  31.     int diameterOfBinaryTree(TreeNode* root) {
  32.         if(!root)return 0;
  33.        
  34.       f(root);
  35.         return mx;
  36.        
  37.     }
  38.    
  39.     int f(TreeNode* root)
  40.     {
  41.          if(!root)return 0;
  42.        
  43.         int l = f(root->left);
  44.         int r = f(root->right);
  45.         mx = max(mx , l+r);
  46.         return max(l,r)+1;
  47.     }
  48.    
  49. };
Add Comment
Please, Sign In to add comment