Factor Tree of a given Number | C ++ program to construct Factor Tree for a given number ; Tree node ; Utility function to create a new tree Node ; Constructs factor tree for given value and stores root of tree at given reference . ; the number is factorized ; If we found a factor , we construct left and right subtrees and return . Since we traverse factors starting from smaller to greater , left child will always have smaller factor ; Iterative method to find the height of Binary Tree ; Base Case ; Print front of queue and remove it from queue ; driver program ;
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { struct Node * left , * right ; int key ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return temp ; } void createFactorTree ( struct Node * * node_ref , int v ) { ( * node_ref ) = newNode ( v ) ; for ( int i = 2 ; i < v / 2 ; i ++ ) { if ( v % i != 0 ) continue ; createFactorTree ( & ( ( * node_ref ) -> left ) , i ) ; createFactorTree ( & ( ( * node_ref ) -> right ) , v / i ) ; return ; } } void printLevelOrder ( Node * root ) { if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; while ( q . empty ( ) == false ) { Node * node = q . front ( ) ; cout << node -> key << " ▁ " ; q . pop ( ) ; if ( node -> left != NULL ) q . push ( node -> left ) ; if ( node -> right != NULL ) q . push ( node -> right ) ; } } int main ( ) { int val = 48 ; struct Node * root = NULL ; createFactorTree ( & root , val ) ; cout << " Level ▁ order ▁ traversal ▁ of ▁ " " constructed ▁ factor ▁ tree " ; printLevelOrder ( root ) ; return 0 ; }