6 line easy code to find diameter :D


  • 0
    N
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    
    int ans = 0;
    
    int findDia(TreeNode *root)
    {
        if(!root)   return -1;
        int llen = 1+findDia(root->left);
        int rlen = 1+findDia(root->right);
        int temp = max(llen,rlen);
        int x = max(1+temp,llen+rlen+1);
        ans = max(ans,x);
        return temp;
    }
    
    class Solution {
    public:
        int diameterOfBinaryTree(TreeNode* root) {
            if(!root)   return 0;
            ans = 0;
            int p = findDia(root);
            return ans-1;
        }
    };
    
    

Log in to reply
 

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