Easy Solution using height of a tree


  • 0
    P

    /**

    • Definition for a binary tree node.
    • struct TreeNode {
    • int val;
      
    • TreeNode *left;
      
    • TreeNode *right;
      
    • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
      
    • };
      /
      class Solution {
      public:
      int height(TreeNode
      node,int& s)
      {
      if(node==NULL)
      return 0;
      int x=height(node->left,s);
      int y=height(node->right,s);
      // update the s, because diameter of a
      // tree is nothing but maximum value of
      // (left_height + right_height + 1) for each node
      s=max(s,x+y);
      if(x>y)
      return x+1;
      return y+1;
    }
    int diameterOfBinaryTree(TreeNode* root) {
        if(root==NULL)
            return 0;
        int d=0;
        int h=height(root,d);        
        return d;
        
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.