[LeetCode] Diameter of Binary Tree

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
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;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/30/PS/LeetCode/diameter-of-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.