Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Last active August 29, 2015 14:14
Show Gist options
  • Save dmnugent80/fad356b31e143cc6ff5d to your computer and use it in GitHub Desktop.
Save dmnugent80/fad356b31e143cc6ff5d to your computer and use it in GitHub Desktop.
Get Count of value in Binary Tree
/*
Interview Question:
Here's a binary tree: write a function to return the count of a certain value in the tree
*/
public class TreeNode{
int data;
TreeNode left;
TreeNode right;
public TreeNode(int d){
data = d;
left = null;
right = null;
}
}
public class IntWrapper{
int value = 0;
}
public class BinaryTree{
TreeNode root;
public BinaryTree(){
root = null;
}
public int getCountOfValue(int valueToCount){
//Here is the IntWrapper we will use to simulate pass-by-reference
IntWrapper count = new IntWrapper();
//Assume the tree has been built already, not shown in the code here
getCountOfValueHelper(root, valueToCount, count);
return count.value;
}
public void getCountOfValueHelper(TreeNode node, int valueToCount, IntWrapper count){
//Base case
if (node == null){
return;
}
//In Order traversal
getCountOfValueHelper(node.left, valueToCount, count);
if (node.data == valueToCount){
//Update the count if value is found in current node
count.value = count.value + 1;
}
getCountOfValueHelper(node.right, valueToCount, count);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment