a Bottom-tp c sulution && easy understanding


  • 0
    B
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    int depth(struct TreeNode* root, int *dimeter) {
        if (!root) {
            *dimeter = 0;
            return 0;
        }
        int dm_l, dm_r;
        int d_l = depth(root->left, &dm_l);
        int d_r = depth(root->right, &dm_r);
        // get maximum between left-subtree and right-subtree
        *dimeter = dm_l > dm_r? dm_l: dm_r;
        int root_dm = d_l + d_r;
        // get maximum diameter
        *dimeter = *dimeter > root_dm? *dimeter: root_dm;
        return d_l > d_r? d_l + 1: d_r + 1;
    }
    
    int diameterOfBinaryTree(struct TreeNode* root) {
        int dm;
        depth(root, &dm);
        return dm;
    }
    

    If there is anything wrong with my code, please correct it and let me know.


Log in to reply
 

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