Select a Random Node from a tree with equal probability | Python3 program to Select a Random Node from a tree ; This is used to fill children counts . ; Inserts Children count for each node ; Returns number of children for root ; Helper Function to return a random node ; Returns Random node ; Driver Code ; Creating Above Tree
from random import randint NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . children = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getElements ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( getElements ( root . left ) + getElements ( root . right ) + 1 ) NEW_LINE DEDENT def insertChildrenCount ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return NEW_LINE DEDENT root . children = getElements ( root ) - 1 NEW_LINE insertChildrenCount ( root . left ) NEW_LINE insertChildrenCount ( root . right ) NEW_LINE DEDENT def children ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return 0 NEW_LINE DEDENT return root . children + 1 NEW_LINE DEDENT def randomNodeUtil ( root , count ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if count == children ( root . left ) : NEW_LINE INDENT return root . data NEW_LINE DEDENT if count < children ( root . left ) : NEW_LINE INDENT return randomNodeUtil ( root . left , count ) NEW_LINE DEDENT return randomNodeUtil ( root . right , count - children ( root . left ) - 1 ) NEW_LINE DEDENT def randomNode ( root ) : NEW_LINE INDENT count = randint ( 0 , root . children ) NEW_LINE return randomNodeUtil ( root , count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = Node ( 10 ) NEW_LINE root . left = Node ( 20 ) NEW_LINE root . right = Node ( 30 ) NEW_LINE root . left . right = Node ( 40 ) NEW_LINE root . left . right = Node ( 50 ) NEW_LINE root . right . left = Node ( 60 ) NEW_LINE root . right . right = Node ( 70 ) NEW_LINE insertChildrenCount ( root ) NEW_LINE print ( " A ▁ Random ▁ Node ▁ From ▁ Tree ▁ : " , randomNode ( root ) ) NEW_LINE DEDENT