6-line C++ DFS Solution


  • 0
    /**
     * 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 n; // primitive member variable will be initialized to 0
        int diameterOfBinaryTree(TreeNode* root) {
            root? DFS(root) : 0;
            return n;
        }
        
        int DFS(TreeNode* p) {
            int l=p->left?DFS(p->left)+1:0, r=p->right?DFS(p->right)+1:0;
            n=max(n,l+r);
            return max(l,r);
        }
    };
    

Log in to reply
 

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