1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
class Solution { public: int diameterOfBinaryTree(TreeNode* root) { if(!root) return 0; queue<TreeNode*> q; q.push(root); int ret = 0; while(!q.empty()) { auto p = q.front(); q.pop(); int dL = 0, dR = 0; if(p->left) { q.push(p->left); maxDepth(p->left, dL, 0); } if(p->right) { q.push(p->right); maxDepth(p->right, dR, 0); } ret = max(ret, dL + dR); } return ret; } private: void maxDepth(TreeNode* root, int& depth, int tmp) { if(!root) return; ++tmp; depth = max(tmp, depth); maxDepth(root->left, depth, tmp); maxDepth(root->right, depth, tmp); --tmp; } };
|