18
1
The height of a binary tree is the distance from the root node to the node child that is farthest from the root.
Below is an example:
2 <-- root: Height 1
/ \
7 5 <-- Height 2
/ \ \
2 6 9 <-- Height 3
/ \ /
5 11 4 <-- Height 4
Height of binary tree: 4
Definition of a Binary Tree
A tree is an object that contains a signed integer value and either two other trees or pointers to them.
The structure of the binary tree struct looks something like the following:
typedef struct tree
{
struct tree * l;
struct tree * r;
int v;
} tree;
The challenge:
Input
The root of a binary tree
Output
The number that represents the height of a binary tree
Assuming you are given the root of a binary tree as input, write the shortest program that calculates the height of a binary tree and returns the height. The program with least amount of bytes (accounting whitespaces) wins.
4What do languages without pointers take? – Jonathan Allan – 2019-08-04T17:37:39.053
Good question, they take a reference to the instance of the tree object. I think I might want to provide the implementation of a tree object in that case. – T. Salim – 2019-08-04T17:38:25.767
4...but then my tree object could just have a property, say
h
. Might be better to define a specific structure made just of lists for the purpose of this challenge. – Jonathan Allan – 2019-08-04T17:40:35.04311
@T.Salim In the future, please consider posting in the sandbox first.
– wizzwizz4 – 2019-08-04T17:44:38.467Sure wizzwizz4. Will do. – T. Salim – 2019-08-04T17:45:34.847
1So, is a valid representation a list of length 3
[root_value, left_node, right_node]
where each ofleft_node
andright_node
are also binary trees acceptable? It'll be trivial in many languages, but might be fun in some others. – Jonathan Allan – 2019-08-04T17:50:59.973As long as it works as a valid binary tree structure, sure. – T. Salim – 2019-08-04T17:51:31.950
3Can you edit the question to include what constitutes a valid binary structure? Perhaps a definition like
a tree is an object that contains a value and either two other trees or pointers to them
. A definition that is inclusive of languages without objects would also be nice too. – Jo King – 2019-08-04T21:54:43.400Yes, I have added a Definition of Binary Tree section. – T. Salim – 2019-08-04T21:56:28.507
Can we exclude the value part of the tree, since it has no bearing on the challenge itself? – Jo King – 2019-08-04T22:15:08.083
If not, what values can the value be? The struct has only integers, but can they also be strings or trees themselves? – Jo King – 2019-08-04T22:23:05.277
I specified that each node must store a signed integer value. – T. Salim – 2019-08-04T22:26:07.073
Can you please add some more test cases? – Shaggy – 2019-08-05T11:55:49.413