Leetcode 543. Diameter of Binary Tree
阿新 • • 發佈:2018-12-13
文章作者:Tyan
部落格:noahsnail.com | CSDN | 簡書
1. Description
2. Solution
/** * 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 diameterOfBinaryTree(TreeNode* root) { if(!root) { return 0; } int diameter = 0; dfs(root, diameter); return diameter; } private: int dfs(TreeNode* root, int& diameter) { if(!root) { return 0; } int left = dfs(root->left, diameter); int right = dfs(root->right, diameter); diameter = max(diameter, left + right); return max(left, right) + 1; } };