C++ DFS solution


  • 0
    W

    class Solution {
    public:

    int diameterOfBinaryTree(TreeNode* root) {
        int res = 0;
        dfs(root, res);
        return res;
    }
    
    int dfs(TreeNode* root, int& res) {
        if (root == 0) {
            return 0;
        }
        int lheight = dfs(root->left, res);
        int rheight = dfs(root->right, res);
        res = max(res, lheight+rheight);
        return 1 + max(lheight, rheight);
    }
    

    };


Log in to reply
 

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