Factor Tree of a given Number | Java program to conFactor 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 conleft 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 ; int val = 48 ; sample value
import java . util . * ; class GFG { static class Node { Node left , right ; int key ; } ; static Node root ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; temp . left = temp . right = null ; return temp ; } static Node createFactorTree ( Node node_ref , int v ) { ( node_ref ) = newNode ( v ) ; for ( int i = 2 ; i < v / 2 ; i ++ ) { if ( v % i != 0 ) continue ; node_ref . left = createFactorTree ( ( ( node_ref ) . left ) , i ) ; node_ref . right = createFactorTree ( ( ( node_ref ) . right ) , v / i ) ; return node_ref ; } return node_ref ; } static void printLevelOrder ( Node root ) { if ( root == null ) return ; Queue < Node > q = new LinkedList < > ( ) ; q . add ( root ) ; while ( q . isEmpty ( ) == false ) { Node node = q . peek ( ) ; System . out . print ( node . key + " ▁ " ) ; q . remove ( ) ; if ( node . left != null ) q . add ( node . left ) ; if ( node . right != null ) q . add ( node . right ) ; } } public static void main ( String [ ] args ) { root = null ; root = createFactorTree ( root , val ) ; System . out . println ( " Level ▁ order ▁ traversal ▁ of ▁ " + " constructed ▁ factor ▁ tree " ) ; printLevelOrder ( root ) ; } }