Last active
August 29, 2015 14:14
-
-
Save dmnugent80/fad356b31e143cc6ff5d to your computer and use it in GitHub Desktop.
Get Count of value in Binary Tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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