Easy and short C++ Solution


  • 0
    M
    int diameterOfBinaryTree(TreeNode* root) {
            if(root==NULL) return 0;
            int res=0;
            DFS(root, res);
            return res-1;
        }
        
        int DFS(TreeNode* root, int& res){
            if(root==NULL) return 0;
            int l=DFS(root->left, res);
            int r=DFS(root->right, res);
            if(l+r+1>res) res=l+r+1;
            return max(l, r)+1;
        }

Log in to reply
 

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