543. Diameter of Binary Tree
Given the root
of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root
.
The length of a path between two nodes is represented by the number of edges between them.
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
|
class Solution { int dfs(TreeNode* node, int& res, int dep) { int now = 0, ma = dep; if(node->left) { int x = dfs(node->left, res, dep + 1); now += x - dep; ma = max(ma, x); } if(node->right) { int x = dfs(node->right, res, dep + 1); now += x - dep; ma = max(ma, x); } res = max(res, now); return ma; } public: int diameterOfBinaryTree(TreeNode* root) { int res = 0; res = max(res, dfs(root, res, 0)); return res; } };
|