/* Tree structure: 1 / \ 2 3 / / \ 4 5 6 */ #include <stdio.h> int depth(int node, int parent[], int root) { int d = 0; while (node != root) { node = parent[node]; d++; } return d; } int main() { int parent[7] = {0, 0, 1, 1, 2, 3, 3}; int root = 1; int node = 5; printf("%d", depth(node, parent, root)); return 0; }
The depth of a node is the number of edges from the node to the root.
Node 5's parent is 3, and 3's parent is 1 (the root). So depth = 2.
/* Tree structure:
10
/ \
5 15
/ \ \
3 7 18
*/Leaf nodes are nodes without children.
Nodes 3, 7, and 18 have no children, so they are leaves.
/* Tree structure: 1 / \ 2 3 / \ 4 5 */ #include <stdio.h> int max(int a, int b) { return (a > b) ? a : b; } int height(int node, int left[], int right[]) { if (node == 0) return -1; return 1 + max(height(left[node], left, right), height(right[node], left, right)); } int main() { int left[6] = {0, 2, 4, 0, 0, 0}; int right[6] = {0, 3, 5, 0, 0, 0}; int node = 2; printf("%d", height(node, left, right)); return 0; }
Node 2 has children 4 and 5, both leaves.
Height is 1 + max(height(4), height(5)) = 1 + max(0, 0) = 1.
But since height of leaf is 0, height of node 2 is 1 + 0 = 1.
Wait, code returns -1 for null, so leaf height is 0.
So height of node 2 is 1 + max(0,0) = 1.
/* Tree structure:
1
/ \
2 3
/ \
6 7
*/Root (1) is level 0.
Node 3 is level 1.
Node 7 is child of 3, so level 2.
#include <stdio.h> int height(int node, int left[], int right[]) { if (node == 0) return 0; return 1 + (height(left[node], left, right) + height(right[node], left, right)); } int main() { int left[6] = {0, 2, 4, 0, 0, 0}; int right[6] = {0, 3, 5, 0, 0, 0}; int node = 1; printf("%d", height(node, left, right)); return 0; }
The code adds heights of left and right subtrees instead of taking the maximum.
This causes the height to be larger than actual height.
