Given a binary tree of N nodes. Count the frequency of an integer K in the binary tree.
Examples:
Input: N = 7, K = 2
1
/ \
2 3
/ \ / \
4 2 2 5
Output: 3
Explanation: 2 occurs 3 times in the tree.
Input: N = 6, K = 5
1
/ \
4 5
/ \ / \
5 6 2 4
Output: 2
Explanation: 5 occurs 2 times in the tree.
Approach: The solution to the problem is based on the traversal of the given binary tree. Follow the steps as shown below:
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* left;
struct Node* right;
Node( int data)
{
this ->data = data;
left = right = NULL;
}
};
int countOccurrence( struct Node* root, int K)
{
stack<Node*> s;
Node* curr = root;
int count = 0;
while (curr != NULL || s.empty() == false ) {
while (curr != NULL) {
s.push(curr);
curr = curr->left;
}
curr = s.top();
s.pop();
if (curr->data == K)
count++;
curr = curr->right;
}
return count;
}
int main()
{
struct Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(2);
root->left->left = new Node(4);
root->left->right = new Node(2);
int K = 2;
int ans = countOccurrence(root, K);
cout << ans << endl;
return 0;
}
|
Java
import java.util.*;
class Node {
int data;
Node left;
Node right;
Node( int data)
{
this .data = data;
left = right = null ;
}
}
class GFG {
public static int countOccurrence(Node root, int K)
{
Stack<Node> s = new Stack<Node>();
Node curr = root;
int count = 0 ;
while (curr != null || s.empty() == false ) {
while (curr != null ) {
s.push(curr);
curr = curr.left;
}
curr = s.peek();
s.pop();
if (curr.data == K)
count++;
curr = curr.right;
}
return count;
}
public static void main(String[] args)
{
Node root = new Node( 1 );
root.left = new Node( 2 );
root.right = new Node( 2 );
root.left.left = new Node( 4 );
root.left.right = new Node( 2 );
int K = 2 ;
int ans = countOccurrence(root, K);
System.out.println(ans);
}
}
|
Python3
class Node:
def __init__( self ,d):
self .data = d
self .left = None
self .right = None
def countOccurrence(root, K):
s = []
curr = root
count = 0
while (curr ! = None or len (s) ! = 0 ):
while (curr ! = None ):
s.append(curr)
curr = curr.left
curr = s[ len (s) - 1 ]
s.pop()
if (curr.data = = K):
count + = 1
curr = curr.right
return count
root = Node( 1 )
root.left = Node( 2 )
root.right = Node( 2 )
root.left.left = Node( 4 )
root.left.right = Node( 2 )
K = 2
ans = countOccurrence(root, K)
print (ans)
|
C#
using System;
using System.Collections.Generic;
public class Node {
public int data;
public Node left;
public Node right;
public Node( int data)
{
this .data = data;
left = right = null ;
}
}
class GFG {
public static int countOccurrence(Node root, int K)
{
Stack<Node> s = new Stack<Node> ();
Node curr = root;
int count = 0;
while (curr != null || s.Count!=0) {
while (curr != null ) {
s.Push(curr);
curr = curr.left;
}
curr = s.Peek();
s.Pop();
if (curr.data == K)
count++;
curr = curr.right;
}
return count;
}
public static void Main () {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(2);
root.left.left = new Node(4);
root.left.right = new Node(2);
int K = 2;
int ans = countOccurrence(root, K);
Console.WriteLine(ans);
}
}
|
Javascript
<script>
class Node {
constructor(d) {
this .data = d;
this .left = null ;
this .right = null ;
}
};
function countOccurrence(root, K) {
let s = [];
let curr = root;
let count = 0;
while (curr != null || s.length != 0) {
while (curr != null ) {
s.push(curr);
curr = curr.left;
}
curr = s[s.length - 1];
s.pop();
if (curr.data == K)
count++;
curr = curr.right;
}
return count;
}
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(2);
root.left.left = new Node(4);
root.left.right = new Node(2);
let K = 2;
let ans = countOccurrence(root, K);
document.write(ans + '<br>')
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Another Approach(using Recursion):
follow the below steps to solve the given problem recursively:
1) traverse the given binary tree in preorder fashion and keep track to count at each node
2) if the current node value is equal to given value(K) then increment k
3) recursively call for left and right subtree.
4) print count answer.
Below is the implementation of above approach:
C++
#include<bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* left;
struct Node* right;
Node( int data)
{
this ->data = data;
left = right = NULL;
}
};
void countOccurrence(Node* root, int K, int &count){
if (root == NULL) return ;
if (root->data == K) count++;
countOccurrence(root->left, K, count);
countOccurrence(root->right, K, count);
}
int main()
{
struct Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(2);
root->left->left = new Node(4);
root->left->right = new Node(2);
int K = 2;
int ans = 0;
countOccurrence(root, K, ans);
cout << ans << endl;
return 0;
}
|
Java
import java.io.*;
class Node {
int data;
Node left;
Node right;
Node( int data)
{
this .data = data;
this .left = null ;
this .right = null ;
}
}
class GFG {
static int count = 0 ;
public static void countOccurrence(Node root, int k)
{
if (root == null )
return ;
if (root.data == k)
count++;
countOccurrence(root.left, k);
countOccurrence(root.right, k);
}
public static void main(String[] args)
{
Node root = new Node( 1 );
root.left = new Node( 2 );
root.right = new Node( 2 );
root.left.left = new Node( 4 );
root.left.right = new Node( 2 );
int k = 2 ;
int ans = 0 ;
countOccurrence(root, k);
System.out.println(count);
}
}
|
Python
class Node:
def __init__( self ,key):
self .data = key
self .left = None
self .right = None
count = 0
def countOccurrence(root, K):
if (root is None ):
return
if (root.data = = K):
global count
count = count + 1
countOccurrence(root.left, K)
countOccurrence(root.right, K)
root = Node( 1 )
root.left = Node( 2 )
root.right = Node( 2 )
root.left.left = Node( 4 )
root.left.right = Node( 2 )
K = 2
countOccurrence(root, K)
print (count)
|
C#
using System;
using System.Collections.Generic;
class Gfg
{
static int count = 0;
class Node {
public int data;
public Node left;
public Node right;
public Node( int data)
{
this .data = data;
left = right = null ;
}
}
static void countOccurrence(Node root, int K)
{
if (root == null )
return ;
if (root.data == K)
count++;
countOccurrence(root.left, K);
countOccurrence(root.right, K);
}
public static void Main( string [] args)
{
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(2);
root.left.left = new Node(4);
root.left.right = new Node(2);
int K = 2;
countOccurrence(root, K);
Console.Write(count);
}
}
|
Javascript
class Node{
constructor(data){
this .data = data;
this .left = null ;
this .right = null ;
}
}
let count = 0;
function countOccurrence(root, K){
if (root == null ) return ;
if (root.data == K) count++;
countOccurrence(root.left, K);
countOccurrence(root.right, K);
}
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(2);
root.left.left = new Node(4);
root.left.right = new Node(2);
let K = 2;
countOccurrence(root, K);
console.log(count);
|
Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(h) where h is the height of the given tree due to recursion.
Another Iterative and Easiest Approach(Using Level Order Traversal with Queue):
Follow the below steps to solve the given problem:
- Perform level order traversal using Queue data structure.
- At each node in traversal check if it is equal to the given integer k then increment the count variable which is initialized by 0 in starting the level order traversal.
- Simply return the value of count variable.
Below is the implementation of above approach:
C++
#include<bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* left;
struct Node* right;
Node( int data)
{
this ->data = data;
left = right = NULL;
}
};
void countOccurrence(Node* root, int K, int &count){
queue<Node*> q;
q.push(root);
while (!q.empty()){
Node* front_node = q.front();
q.pop();
if (front_node->data == K) count++;
if (front_node->left) q.push(front_node->left);
if (front_node->right) q.push(front_node->right);
}
}
int main()
{
struct Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(2);
root->left->left = new Node(4);
root->left->right = new Node(2);
int K = 2;
int ans = 0;
countOccurrence(root, K, ans);
cout << ans << endl;
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left;
Node right;
Node( int data) {
this .data = data;
left = right = null ;
}
}
public class Main {
static void countOccurrence(Node root, int K, int [] count) {
Queue<Node> q = new LinkedList<Node>();
q.add(root);
while (!q.isEmpty()) {
Node front_node = q.poll();
if (front_node.data == K) {
count[ 0 ]++;
}
if (front_node.left != null ) {
q.add(front_node.left);
}
if (front_node.right != null ) {
q.add(front_node.right);
}
}
}
public static void main(String[] args) {
Node root = new Node( 1 );
root.left = new Node( 2 );
root.right = new Node( 2 );
root.left.left = new Node( 4 );
root.left.right = new Node( 2 );
int K = 2 ;
int [] ans = { 0 };
countOccurrence(root, K, ans);
System.out.println(ans[ 0 ]);
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def countOccurrence(root, k):
if root is None :
return 0
count = 0
queue = []
queue.append(root)
while ( len (queue) > 0 ):
node = queue.pop( 0 )
if (node.data = = k):
count + = 1
if node.left is not None :
queue.append(node.left)
if node.right is not None :
queue.append(node.right)
return count
if __name__ = = '__main__' :
root = Node( 1 )
root.left = Node( 2 )
root.right = Node( 2 )
root.left.left = Node( 4 )
root.left.right = Node( 2 )
k = 2
print (countOccurrence(root, k))
|
C#
using System;
using System.Collections.Generic;
public class Node {
public int data;
public Node left, right;
public Node( int item) {
data = item;
left = right = null ;
}
}
public class BinaryTree {
Node root;
public void CountOccurrence( int k, ref int count) {
if (root == null )
return ;
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(root);
while (queue.Count > 0) {
Node frontNode = queue.Dequeue();
if (frontNode.data == k)
count++;
if (frontNode.left != null )
queue.Enqueue(frontNode.left);
if (frontNode.right != null )
queue.Enqueue(frontNode.right);
}
}
public static void Main( string [] args) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(2);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(2);
int k = 2;
int count = 0;
tree.CountOccurrence(k, ref count);
Console.WriteLine(count);
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .left = null ;
this .right = null ;
}
}
function countOccurrence(root, K) {
let count = 0;
let q = [];
q.push(root);
while (q.length > 0){
let front_node = q.shift();
if (front_node.data == K) count++;
if (front_node.left) q.push(front_node.left);
if (front_node.right) q.push(front_node.right);
}
return count;
}
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(2);
root.left.left = new Node(4);
root.left.right = new Node(2);
let K = 2;
let ans = countOccurrence(root, K);
console.log(ans);
|
Time Complexity: O(N) where N is the number of nodes in given Binary tree because we simply traverse the each node only once.
Auxiliary space: O(N) due to queue data structure for storing the node level-wise.
Please Login to comment...