Bootstrap

二叉树的直径

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    int len;
public:
    int dfs(TreeNode* root){
        if(root->left == nullptr && root->right == nullptr) return 1;
        int l = 0, r = 0;
        if(root->left) l = dfs(root->left);
        if(root->right) r = dfs(root->right);
        len = max(len, l + r);
        return max(l, r) + 1;
    }
    int diameterOfBinaryTree(TreeNode* root) {
        len = 0;
        if(root == nullptr) return len;
        dfs(root);
        return len;
    }
};
;