c++ Solution. Super clean and easy to understand

  • 0

    Use DFS to compute the depth of each node. In each recursion, backtrack and update the diameter in realtime.

    class Solution {
        int diameterOfBinaryTree(TreeNode* root) {
            int result = 0;
            depth(root, result);
            return result;
        int depth(TreeNode* node, int& diameter) {
            if (!node) return 0;
            int left = depth(node->left, diameter);
            int right = depth(node->right, diameter);
            diameter = max(diameter, left + right);
            return max(left, right) + 1;

Log in to reply

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