s4553711
4/25/2017 - 2:51 PM

543.cpp

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