Binary Trees Count Number of Leaves - algorithm

Suppose you already have the basic binary tree procedures isempty(bt), root(bt), left(bt), and right(bt). Write a procedure isLeaf(bt) that returns true if the binary tree bt is a leaf node and false if it is not.
This is what I have:
proc isLeaf(bt)
if (isEmpty(bt))
error('The binary tree is empty.');
elseif (left(bt) < right(bt))
return true;
else return false;
Then write a procedure numLeaves(bt) that returns the number of leaves in the binary tree bt.
This is what I have:
proc numLeaves(bt)
if (isEmpty(bt))
error ('The binary tree is empty.');
elseif (count left(bt) + right(bt));
return (left(bt) + right(bt);
please could you correct?

You'll learn very little to nothing if you don't try to solve this yourself, but just for people coming here looking for an answer:
boolean isLeaf (BinaryTree bt) {
return !isempty(bt) && isempty(left(bt)) && isempty(right(bt));
}
int numLeaves (BinaryTree bt) {
if (isempty(bt))
return 0;
else if (isLeaf(bt))
return 1;
else
return numLeaves(left(bt)) + numLeaves(right(bt));
}

The main idea here is to use recursion:
The number of leaves a node has is the sum of the number of leaves its left child has, and the number of leaves its right child has.

As #jeffrey greenham said that we can use recursion
int countleaves(struct node* root){
if(root!=null)
{
countleaves(root->left);
if(root->left==NULL&&root->right==NULL)
{
count++;
}
countleaves(root->right);
}
}

Related

Returning an element with a specific rank k in a binary tree

I already implemented a method rankOfElement(x) in pseudocode which returns the rank for a given node x:
function rankofElement(x) {
rank = 0;
Node temp = root;
while (temp.key != x) {
if (x < temp.key) {
temp = temp.leftson
} else if (x > temp.key) {
rank += temp.leftson.size + 1;
temp = temp.rightson;
} else if (temp.key == x) {
return rank + temp.leftson.size
} else return "key not found"
}
Now I should implement a method (elementbyRank(k)) in pseudocode which returns a node with a specific rank k in the context of a binary tree.
I am struggling with that and I hope you can give me an answer.
So, if given rank k and we need to find a node with the given rank we first need a traversal algorithm to search through the tree. A pre-order traversal should work just fine. Here is a recursive one.
function preOrderTraversal(node){
if(node !== null){
print(node.data);
preOrderTraversal(node.left);
preOrderTraversal(node.right);
}
}
now that we have a way to get through our tree we need to implement the elementbyRank method and modify the traversal algorithm. Instead of printing the data we will check each node's rank. we will need to pass rank we need to find and we will need to add a return to the traversal.
The elementbyRank method is pretty simple:
function elementbyRank(k){
return preOrderTraversal(root, k);
}
Now we need to make the changes to the prePrderTraveral and let's change the name as well to elementbyRankTraversal.
function elementbyRankTraversal(node, key){
if(node !== null){
if(key == rankofElement(node.key))
return node;
return elementbyRankTraversal(node.left);
return elementbyRankTraversal(node.right);
}
return null;
}
So now if we find a node with the passed in rank, we will get that node back. but if one does not exist we will instead get a null value.
I know that you said given node x, the rankofElement(x) will return the rank of the element. but you are comparing the node's key directly to x which tell me that x is not a node but x is the key of node x. If I'm wrong then just remove the key part from elementbyRankTraversal().
And that should work.

How to calculate a height of a tree

I am trying to learn DSA and got stuck on one problem.
How to calculate height of a tree. I mean normal tree, not any specific implementation of tree like BT or BST.
I have tried google but seems everyone is talking about Binary tree and nothing is available for normal tree.
Can anyone help me to redirect to some page or articles to calculate height of a tree.
Lets say a typical node in your tree is represented as Java class.
class Node{
Entry entry;
ArrayList<Node> children;
Node(Entry entry, ArrayList<Node> children){
this.entry = entry;
this.children = children;
}
ArrayList<Node> getChildren(){
return children;
}
}
Then a simple Height Function can be -
int getHeight(Node node){
if(node == null){
return 0;
}else if(node.getChildren() == null){
return 1;
} else{
int childrenMaxHeight = 0;
for(Node n : node.getChildren()){
childrenMaxHeight = Math.max(childrenMaxHeight, getHeight(n));
}
return 1 + childrenMaxHeight;
}
}
Then you just need to call this function passing the root of tree as argument. Since it traverse all the node exactly once, the run time is O(n).
1. If height of leaf node is considered as 0 / Or height is measured depending on number of edges in longest path from root to leaf :
int maxHeight(treeNode<int>* root){
if(root == NULL)
return -1; // -1 beacuse since a leaf node is 0 then NULL node should be -1
int h=0;
for(int i=0;i<root->childNodes.size();i++){
temp+=maxHeight(root->childNodes[i]);
if(temp>h){
h=temp;
}
}
return h+1;
}
2. If height of root node is considered 1:
int maxHeight(treeNode<int>* root){
if(root == NULL)
return 0;
int h=0;
for(int i=0;i<root->childNodes.size();i++){
temp+=maxHeight(root->childNodes[i]);
if(temp>h){
h=temp;
}
}
return h+1;
Above Code is based upon following class :
template <typename T>
class treeNode{
public:
T data;
vector<treeNode<T>*> childNodes; // vector for storing pointer to child treenode
creating Tree node
treeNode(T data){
this->data = data;
}
};
In case of 'normal tree' you can recursively calculate the height of tree in similar fashion to a binary tree but here you will have to consider all children at a node instead of just two.
To find a tree height a BFS iteration will work fine.
Edited form Wikipedia:
Breadth-First-Search(Graph, root):
create empty set S
create empty queues Q1, Q2
root.parent = NIL
height = -1
Q1.enqueue(root)
while Q1 is not empty:
height = height + 1
switch Q1 and Q2
while Q2 is not empty:
for each node n that is adjacent to current:
if n is not in S:
add n to S
n.parent = current
Q1.enqueue(n)
You can see that adding another queue allows me to know what level of the tree.
It iterates for each level, and for each mode in that level.
This is a discursion way to do it (opposite of recursive). So you don't have to worry about that too.
Run time is O(|V|+ |E|).

Find kth min node in AVL tree

I now have built a AVL tree, Here is a function to find kth min node in AVL tree
(k started from 0)
Code:
int kthMin(int k)
{
int input=k+1;
int count=0;
return KthElement(root,count,input);
}
int KthElement( IAVLTreeNode * root, int count, int k)
{
if( root)
{
KthElement(root->getLeft(), count,k);
count ++;
if( count == k)
return root->getKey();
KthElement(root->getRight(),count,k);
}
return NULL;
}
It can find some of right nodes, but some may fail, anyone can help me debug this>
THanks
From the root, after recursing left, count will be 1, regardless of how many nodes are on the left.
You need to change count in the recursive calls, so change count to be passed by reference (assuming this is C++).
int KthElement( IAVLTreeNode * root, int &count, int k)
(I don't think any other code changes are required to get pass by reference to work here).
And beyond that you need to actually return the value generated in the recursive call, i.e. change:
KthElement(root->getLeft(), count, k);
to:
int val = KthElement(root->getLeft(), count, k);
if (val != 0)
return val;
And similarly for getRight.
Note I used 0, not NULL. NULL is typically used to refer to a null pointer, and it converts to a 0 int (the latter is preferred when using int).
This of course assumes that 0 isn't a valid node in your tree (otherwise your code won't work). If it is, you'll need to find another value to use, or a pointer to the node instead (in which case you can use NULL to indicate not found).
Here is simple algorithm for Kth smallest node in any tree in general:-
count=0, found=false;
kthElement(Node p,int k) {
if(p==NULL)
return -1
else {
value = kthElement(p.left)
if(found)
return value
count++
if(count==k) {
found = true
return p.value
}
value = kthElement(p.right)
return value
}
}
Note:- Use of global variables is the key.

Amazon Interview:Sum of the leaf node in BST

Code Which I have written for this :
sumBST(BST *root)
{
static sum =0;
if (root!= null)
{
if (root->left != null || root->right != null)
{
sum = sum + sumBST(root->left) + sumBST(root->right);
return sum;
}
else
{
root->data;
}
}
else
{
return 0;
}
return sum;
}
I have checked it by drawing recursion tree seems well but Still i am confused at some point I am doing some mistake. Please correct me i am doing something wrong here.
Well, it doesn't seem like you are actually adding the sum of the leaf nodes.
In parcticular - the line:
root->data
Does not actually return the data, just reads it.
Should be something like that in pseudo code:
sumBST(node):
if (root == null):
return 0
else if (root->left == null && root->right == null)
//add the value of the node if it is a leaf, this step is missing
return root->data;
else:
return sumBST(root->left) + sumBST(root->right)
EDIT:
The problem in the code are as follows (clarifying and explaining further that point in the answer):
You should return the data of the leaves somewhere - this is not happening anywhere in the code - I suspect you wanted to return it in root->data.
However note that the recursion will go to each and every leaf - it is just missing returning the value from each of them.
The purpose of such question is mainly focused on assessing the candidate thinking process.
All I see here is a typo error
root->data => return root->data
and an instruction that is never reached
return sum;
and one excessively long instruction
sum = sum + sumBST(root->left) + sumBST(root->right); => return sumBST(root->left) + sumBST(root->right);
Interviewers always like to get questioned about the problems they give.
A question like "Is the BST given or can I design a structure that is optimized toward given the sum of leaf?", "How big is the BST?"... Can add a plus and most likely change completely your answer.

How to count the number of right children in a binary tree?

How to count the number of right children in a binary tree?
This means that I only want the children marked as right.
Ex.
(Left | Right)
F(Root)
G | H
T U | I J
The right children would be U,H,and J.
What would be the algorithm to find these.
int count(Tree *r){
if(r == NULL) return 0;
int num_l=0, num_r=0;
if(r->left != NULL)
num_l = count(r->left);
if(r->right != NULL)
num_r = count(r->right)+1;
return num_l+num_r
}
In recursive approach,
You would be calling a function to traverse your tree,
for current node, you need to:
check if current node has right child (then increment the counter), and then call the function recursively for right node.
check if current node has left child, call the function recursively for left node.
This should work.
Do a simple traversal on the tree (i.e. post order, in order) and for each node do +1 if it has right child.
Example (didn't try to compile and check it):
int countRightChildren(Node root)
{
if (root == null) return 0;
int selfCount = (root.getRightChild() != null) ? 1 : 0;
return selfCount + countRightChildren(root.getLeftChild()) + countRightChildren(root.getRightChild());
}
You can do it recursively as:
If tree does not exist, there are no
R children.
If tree exists, then # R children = #
R children in R-subtree + # R
children in L-subtree
.
int countRChildren(Node *root) {
if(!root) // tree does not exist.
return 0;
// tree exists...now see if R node exits or not.
if(root->right) // right node exist
// return 1 + # of R children in L/R subtree.
return 1 + countRChildren(root->right) + countRChildren(root->left);
else // right nodes does not exist.
// total count of R children will come from left subtree.
return countRChildren(root->left);
}
This is include how i build the struct
struct Item
{
int info;
struct Item* right;
struct Item* left;
};
typedef struct Item* Node;
int countRightSons(Node tree)
{
if(!tree)
return 0;
if(tree->right != NULL)
return 1 + countRightSons(tree->right) + countRightSons(tree->left);
return countRightSons(tree->left);
}
Simple recursive approach,
check (even if not needed) for all the 4 possibilities:
left and right does not exists
left and right exists
left exists and right doesnt
right exists and left doesnt
public static int countRightChildren(BST tree) {
if (tree.root==null) return Integer.MIN_VALUE;
return countRightChildren(tree.root);}
public static int countRightChildren(Node curr) {
if (curr.right==null&&curr.left==null) return 0;
else if (curr.right!=null&&curr.left==null)
return curr.right.data+countRightChildren(curr.right);
else if (curr.right==null&&curr.left!=null)
return countRightChildren(curr.left);
else if (curr.right!=null&&curr.left!=null)
return curr.right.data+countRightChildren(curr.left)+countRightChildren(curr.right);
return Integer.MIN_VALUE;
}

Resources