[AlgoExpert] All Kinds Of Node Depths

All Kinds Of Node Depths

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

class BinaryTree {
public:
int value;
BinaryTree *left;
BinaryTree *right;

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

void helper(BinaryTree* node, int& res, int depth = 0) {
if(!node) return;
res += depth * (depth + 1) / 2;
helper(node->left, res, depth + 1);
helper(node->right, res, depth + 1);
return;
}

int allKindsOfNodeDepths(BinaryTree *root) {
int res = 0;
helper(root, res);
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/all-kinds-of-node-depths/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.