Given a Binary Tree, the task is to output the Count of the number of paths formed by only a Triangular number. Xth Triangular number is the sum of the first X natural numbers. Example: {1, 3, 6, 10 . . .} are triangular numbers.
Note: Path should be from root to node.
Examples:
Input:
First test case
Output: 1
Explanation: The path formed by only Triangular numbers is {1 → 3 → 6 → 10}.
Input:
Second test case
Output: 2
Explanation: There are 2 paths formed by only Triangular number which are {1 → 3 → 6} and {1 → 3 → 6 → 10}.
Approach: Implement the idea below to solve the problem
The idea to solve this problem is to generate a sequence of Triangular numbers based on the height of the tree and then traversing the tree in a Preorder traversal to identify paths that match this sequence.
Follow the steps to solve the problem:
Calculates the height of the tree recursively.
Initializes the Triangular number sequence based on the height of the tree to count the paths satisfying the condition.
In Preorder traversal, If the current node is NULL or if the node's value does not match the triangular number at the current node, then:
Return the current count as it is.
If it is a leaf node
Increment the count of paths.
Recursively call for the left and right subtree with the updated count.
After all-recursive call, the value of Count is number of triangular number paths for a given binary tree.
Below is the code to implement the above approach:
C++14
// C++ Code to implement the approach#include<bits/stdc++.h>usingnamespacestd;// Build tree classclassNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=NULL;right=NULL;}};// Function to find the height// of the given treeintgetHeight(Node*root){// Base case: if the root is// NULL, the height is 0if(root==NULL)return0;// Recursive calls to find height of// left and right subtreesintleftHeight=getHeight(root->left);intrightHeight=getHeight(root->right);// Return the maximum height between left// and right subtrees + 1 for the current nodereturn1+max(leftHeight,rightHeight);}// Function to count paths in the tree where// node values form a triangular number sequenceintcntTriPath(Node*root,intind,vector<int>&triNum,intcount){// Base case:// If the current node is NULL or its value// does not match the triangular number at index 'ind'if(root==NULL||!(triNum[ind]==root->data)){returncount;// Return the current count}// Check if the current node is a leaf nodeif(root->left==NULL&&root->right==NULL){// Increment count as it forms a valid pathcount++;}// Recursive call to explore left// subtree and right subtreecount=cntTriPath(root->left,ind+1,triNum,count);returncntTriPath(root->right,ind+1,triNum,count);}// Function to count paths in the tree where// node values form a triangular number sequenceintCountTriangularNumberPath(Node*root){// Get the height of the treeintn=getHeight(root);vector<int>triNum;intcurrent_level=1;inttriangular_number=0;// Generating the triangular number sequence// based on tree heightfor(inti=1;i<=n;i++){// Add the current level to the// triangular numbertriangular_number+=current_level;triNum.push_back(triangular_number);// Incrementing current levelcurrent_level++;}// Call the function to count paths satisfying// the triangular number sequence conditionintcntPath=cntTriPath(root,0,triNum,0);returncntPath;}// Driver codeintmain(){// Example tree creationNode*root=newNode(1);root->left=newNode(3);root->right=newNode(3);root->left->left=newNode(2);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);root->right->left->right=newNode(10);// Finding number of paths and// printing the resultintans=CountTriangularNumberPath(root);cout<<ans;return0;}
Java
// Java program for the above approachimportjava.util.ArrayList;importjava.util.List;// Build tree classclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}publicclassGFG{// Function to find the height of the given treestaticintgetHeight(Noderoot){// Base case: if the root is NULL, the height is 0if(root==null)return0;// Recursive calls to find height of left and right// subtreesintleftHeight=getHeight(root.left);intrightHeight=getHeight(root.right);// Return the maximum height between left and right// subtrees + 1 for the current nodereturn1+Math.max(leftHeight,rightHeight);}// Function to count paths in the tree where node values// form a triangular number sequencestaticintcountTriPath(Noderoot,intind,List<Integer>triNum,intcount){// Base case:// If the current node is NULL or its value does not// match the triangular number at index 'ind'if(root==null||!(triNum.get(ind)==root.data)){returncount;// Return the current count}// Check if the current node is a leaf nodeif(root.left==null&&root.right==null){// Increment count as it forms a valid pathcount++;}// Recursive call to explore left subtree and right// subtreecount=countTriPath(root.left,ind+1,triNum,count);returncountTriPath(root.right,ind+1,triNum,count);}// Function to count paths in the tree where node values// form a triangular number sequencestaticintcountTriangularNumberPath(Noderoot){// Get the height of the treeintn=getHeight(root);List<Integer>triNum=newArrayList<>();intcurrentLevel=1;inttriangularNumber=0;// Generating the triangular number sequence based// on tree heightfor(inti=1;i<=n;i++){// Add the current level to the triangular// numbertriangularNumber+=currentLevel;triNum.add(triangularNumber);// Incrementing current levelcurrentLevel++;}// Call the function to count paths satisfying the// triangular number sequence conditionintcntPath=countTriPath(root,0,triNum,0);returncntPath;}// Driver codepublicstaticvoidmain(String[]args){// Example tree creationNoderoot=newNode(1);root.left=newNode(3);root.right=newNode(3);root.left.left=newNode(2);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.right.left.right=newNode(10);// Finding the number of paths and printing the// resultintans=countTriangularNumberPath(root);System.out.println(ans);}}// This code is contributed by Susobhan Akhuli
Python3
# Python program for the above approach# Build tree classclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Function to find the height of the given treedefget_height(root):# Base case: if the root is NULL, the height is 0ifrootisNone:return0# Recursive calls to find height of left and right subtreesleft_height=get_height(root.left)right_height=get_height(root.right)# Return the maximum height between left and right subtrees + 1 for the current nodereturn1+max(left_height,right_height)# Function to count paths in the tree where node values form a triangular number sequencedefcount_tri_path(root,ind,tri_num,count):# Base case:# If the current node is NULL or its value does not match the triangular number at index 'ind'ifrootisNoneortri_num[ind]!=root.data:returncount# Return the current count# Check if the current node is a leaf nodeifroot.leftisNoneandroot.rightisNone:# Increment count as it forms a valid pathcount+=1# Recursive call to explore left subtree and right subtreecount=count_tri_path(root.left,ind+1,tri_num,count)returncount_tri_path(root.right,ind+1,tri_num,count)# Function to count paths in the tree where node values form a triangular number sequencedefcount_triangular_number_path(root):# Get the height of the treen=get_height(root)tri_num=[]current_level=1triangular_number=0# Generating the triangular number sequence based on tree heightforiinrange(1,n+1):# Add the current level to the triangular numbertriangular_number+=current_leveltri_num.append(triangular_number)# Incrementing current levelcurrent_level+=1# Call the function to count paths satisfying the triangular number sequence conditioncnt_path=count_tri_path(root,0,tri_num,0)returncnt_path# Driver codeif__name__=="__main__":# Example tree creationroot=Node(1)root.left=Node(3)root.right=Node(3)root.left.left=Node(2)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)root.right.left.right=Node(10)# Finding number of paths and printing the resultans=count_triangular_number_path(root)print(ans)# This code is contributed by Susobhan Akhuli
C#
// C# program for the above approachusingSystem;usingSystem.Collections.Generic;// Build tree classclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}classMainClass{// Function to find the height of the given treestaticintGetHeight(Noderoot){// Base case: if the root is NULL, the height is 0if(root==null)return0;// Recursive calls to find height of left and right// subtreesintleftHeight=GetHeight(root.left);intrightHeight=GetHeight(root.right);// Return the maximum height between left and right// subtrees + 1 for the current nodereturn1+Math.Max(leftHeight,rightHeight);}// Function to count paths in the tree where node values// form a triangular number sequencestaticintCountTriPath(Noderoot,intind,List<int>triNum,intcount){// Base case: If the current node is NULL or its// value does not match the triangular number at// index 'ind'if(root==null||!(triNum[ind]==root.data)){returncount;// Return the current count}// Check if the current node is a leaf nodeif(root.left==null&&root.right==null){// Increment count as it forms a valid pathcount++;}// Recursive call to explore left subtree and right// subtreecount=CountTriPath(root.left,ind+1,triNum,count);returnCountTriPath(root.right,ind+1,triNum,count);}// Function to count paths in the tree where node values// form a triangular number sequencestaticintCountTriangularNumberPath(Noderoot){// Get the height of the treeintn=GetHeight(root);List<int>triNum=newList<int>();intcurrent_level=1;inttriangular_number=0;// Generating the triangular number sequence based// on tree heightfor(inti=1;i<=n;i++){// Add the current level to the triangular// numbertriangular_number+=current_level;triNum.Add(triangular_number);// Incrementing current levelcurrent_level++;}// Call the function to count paths satisfying the// triangular number sequence conditionintcntPath=CountTriPath(root,0,triNum,0);returncntPath;}// Driver codepublicstaticvoidMain(string[]args){// Example tree creationNoderoot=newNode(1);root.left=newNode(3);root.right=newNode(3);root.left.left=newNode(2);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.right.left.right=newNode(10);// Finding number of paths and printing the resultintans=CountTriangularNumberPath(root);Console.WriteLine(ans);}}// This code is contributed by Susobhan Akhuli
JavaScript
// javaScript code for the above approach// Node class to build the tree structureclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Function to find the height of the treefunctiongetHeight(root){if(!root)return0;constleftHeight=getHeight(root.left);constrightHeight=getHeight(root.right);return1+Math.max(leftHeight,rightHeight);}// Function to count paths in the tree where// node values form a triangular number sequencefunctioncntTriPath(root,ind,triNum,count){if(!root||triNum[ind]!==root.data){returncount;}if(!root.left&&!root.right){count++;}count=cntTriPath(root.left,ind+1,triNum,count);returncntTriPath(root.right,ind+1,triNum,count);}// Function to count paths in the tree where// node values form a triangular number sequencefunctionCountTriangularNumberPath(root){constn=getHeight(root);consttriNum=[];letcurrentLevel=1;lettriangularNumber=0;for(leti=1;i<=n;i++){triangularNumber+=currentLevel;triNum.push(triangularNumber);currentLevel++;}constcntPath=cntTriPath(root,0,triNum,0);returncntPath;}// Example tree creationletroot=newNode(1);root.left=newNode(3);root.right=newNode(3);root.left.left=newNode(2);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.right.left.right=newNode(10);// Finding number of paths and// printing the resultletans=CountTriangularNumberPath(root);console.log(ans);
Output
1
Time Complexity: O(N), Where N is the number of nodes in the given tree. Auxiliary Complexity: O(H), Where H is the height of the tree.