This class we work with the simplest type of trees called binary trees.
Each node has a left node and a right node, they both don't have to be filled out but there never can be more of these.
A tree is a type of recursive data structure, that means that even the nodes are trees themselves, so it's right to think about each tree being made up of a left subtree and right subtree.
Since it is a recursive data structure, trees are great for recursive algorithms and trying to do these problems iteratively will be far more complex. This means your code for doing stuff like this will often be short, but tricky to figure out.
It gets better with practice :)
Full binary tree (10 minutes)
Check for full binary tree
That means that each node has either zero children, or two.
publicclassTree{
int value;
Tree left;
Tree right;
}
publicstaticbooleanisHeap(Tree t){
if (t == null) {
returntrue;
}
// check if each branch exists, then first check the immediate value // and after that check the whole subtreeif (t.left != null && t.value < t.left.value && !(isHeap(t.left))) {
returnfalse;
}
if (t.right != null && t.value < t.right.value && !(isHeap(t.right))) {
returnfalse;
}
returntrue;
}