543. Diameter of Binary Tree

/**
 * 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 res = 0;
    int diameterOfBinaryTree(TreeNode* root) {
        helper(root);
        return res;
    }
    int helper(TreeNode* root) {
        if (root == NULL)   return 0;
        int left = helper(root->left) + 1;
        int right = helper(root->right) + 1;
        res = max(res, left+right-2);
        return max(left, right);
    }
};

猜你喜欢

转载自www.cnblogs.com/JTechRoad/p/9108572.html