[AlgoExpert] Binary Tree Diameter

Binary Tree Diameter

  • Time : O(n)
  • Space : O(d)
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
using namespace std;

// This is an input class. Do not edit.
class BinaryTree {
public:
int value;
BinaryTree *left;
BinaryTree *right;

BinaryTree(int value) {
this->value = value;
left = nullptr;
right = nullptr;
}
};

int helper(BinaryTree *node, int& res) {
if(!node) return 0;
int ldepth = helper(node->left, res);
int rdepth = helper(node->right, res);
res = max(res, ldepth + rdepth);
return max(ldepth, rdepth) + 1;
}

int binaryTreeDiameter(BinaryTree *tree) {
int res = -1;
helper(tree, res);
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/17/PS/AlgoExpert/binary-tree-diameter/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.