I have to write methods for a binary tree that has positive integers as values. These are not full methods. They are supposed to be written in pseudocode.
a) Count number of nodes in a Tree
countNodes(TreeNode root){
if(root == null)
return 0;
else{
TreeNode left = root.getLeftChild();
TreeNode right = root.getRightChild();
return (countNodes(left)+countNodes(right)) + 1;
}
}
b) Compute the height of a tree
height(TreeNode root){
if(root == null)
return 0;
else{
return Math.max(height(root.getLeftChild()), height(root.getRightChild()) +1;
}
}
c) Find the maximum element
maxElem(TreeNode root){
if(root == null)
return 0;
else{
int temp = 0;
temp = Math.max(maxElem(root.getLeftChild()), maxElem(root.getRightChild()));
return Math.max(root.getValue, temp);
}
}
d) Find the sum of the elements
sum(TreeNode root){
if(root == null)
return 0;
else{
return (sum(root.getLeftChild()) + sum(root.getRightChild())) + root.getValue();
}
}
e) Find the average of the Elements
average(TreeNode root){
double sum = sum(root);
double elems = countNodes(root);
return sum/elems;
}
f) Find a Specific Item
search(int i, TreeNode root){
if(root == null)
return false;
else if(root.getValue == i)
return true;
else{
return search(i, root.getLeftChild);
return search(i, root.getRightChild);
}
}
g) Determine whether an item is an ancestor of another
isAncestor(TreeNode p, NodeNode c){
if(p==null)
return false;
else
return (c in p.getLeftChild() || c in p.getRightChild())
}
h) Determine the highest level that is full
maxFull(TreeNode root)
if(root == null)
return 0;
else{
return(numNodes in level h == 2^h - 1)
}
}