Question

In: Computer Science

6. Write a function to count a tree’s height, which is the length of the longest...

6. Write a function to count a tree’s height, which is the length of the longest path from the root to a leaf.

Please finish this question in python programming

Solutions

Expert Solution

I hope this is what you want. if you still have any doubt please let me know. I have attached code as well as screen shot. I have created 2 version of this program. both are working perfectly. 1st is for binary tree while 2nd work with any tree.

Version1-------------

class tree:
    def __init__(self,data): # constructor to create new node
        self.left=None
        self.right=None
        self.data=data
    def insert(self,data): #inseting a data in binary search tree
        if self.data:
            if(data<self.data): # if data is less than root then it is in left child
                if self.left is None: #if there is no left child it becomes left child
                    self.left=tree(data)
                else:
                    self.left.insert(data)
            elif data>self.data: # if node has a higher value than root then it is in right child
                if self.right is None: #if there is no right child it becomes right child
                    self.right=tree(data)
                else:
                    self.right.insert(data)
                  
def height(tree):   # height function will count the height of tree
    if tree is None: #if no tree it will return height=0
        return 0 ;
    else :
        lheight = height(tree.left) # recursion which will count the height of left subtree at each node
        rheight = height(tree.right) # recursion which will count the height of right subtree at each node
  
        if (lheight > rheight): # comparing left height and right hight at root node and adding 1 to the greater height
            return lheight+1
        else:
            return rheight+1

y=input("Enter a value of root node for no root press 0 or negartive value= ") # Enter a value of root Node
if int(y)>0:
    root = tree(int(y)) #passing the root node value in tree
    x=1# varible for loop continuiety
    while(int(x)>0):   #if xhas a vale >0 loop continue otherwise loop break
        x=input("Enter a node value >0 for countinue and <=0 for stop=") # asking user for input
        if(int(x)>0): #if input >0 add in binary tree
            root.insert(int(x)) #insert a value in binary search tree    
    print("Height of Binary search tree is "+f'{height(root)}')
else:
    print("Height of Binary search tree is 0 there is no root")

Version 2------------------------------------------------------------------------------

class tree: # class tree for tree
    def __init__(self,data): # constructor to create new node in tree
        self.left=None
        self.right=None
        self.data=data
def height(tree):   # height function will count the height of tree
    if tree is None: #if no tree it will return height=0
        return 0 ;
    else :
        lheight = height(tree.left) # recursion which will count the height of left subtree at each node
        rheight = height(tree.right) # recursion which will count the height of right subtree at each node
  
        if (lheight > rheight): # comparing left height and right hight at root node and adding 1 to the greater height
            return lheight+1
        else:
            return rheight+1
root=tree(50) #creating root node
root.left=tree(40) # creating left child
root.left.left=tree(30)
root.right=tree(60)
root.right.left=tree(59)
root.right.left.left=tree(58)
root.right.left.left.left=tree(57)
root.right.left.left.left.left=tree(56)
height=height(root) # calling heiht function using tree object as argument
print("The height of the tree is "+f'{height}') # printing height of tree

-----------------------------------------------------screenshot----------------------------------------------------------------------------------


Related Solutions

Write a python script to calculate the average length of the game shortest game , longest...
Write a python script to calculate the average length of the game shortest game , longest game and the overall average length of a snake and ladder game The game length is the number of throws of the die. We are asked to write a python script which calculate that together with the average
Write a python script to calculate the average length of the game, Shortest game, longest game...
Write a python script to calculate the average length of the game, Shortest game, longest game and overall length of the game we need a python script that calculates the average length of a snake and ladder game. ie the number of moves it takes a single player to win the game. Then you run the game several times and will compare the results to come up with the required data(length of the game and number of moves )
Main Objective: Create a function collect_statistics to count the number of words and mean length of...
Main Objective: Create a function collect_statistics to count the number of words and mean length of words in each sentence This is my code so far but I am struggling to join the two functions together. I would appreciate the help! The sentence given as an example is : "Haven't you eaten 8 oranges today?" the mean length of this sentence is 4.5 for reference. Each sentence needs to be split up if given multiple sentences, assuming each sentence ends...
In python write a program which prints the longest substring of numbers which occur in ascending...
In python write a program which prints the longest substring of numbers which occur in ascending order s=342153476757561235
Write a PHP program using HTML form. It will take Length, Width and Height of a...
Write a PHP program using HTML form. It will take Length, Width and Height of a box as input. When a button is pressed, it will calculate the Volume. If Volume is less than 25 then display the message “Small box”. If Volume is from 25 to 50, it will display the message “Medium box”. When the Volume is greater than 50, then display the message “Large box”.
Write a function that will receive two input arguments that is the height in inches (in.)...
Write a function that will receive two input arguments that is the height in inches (in.) and the weight in pounds (lb) of a person and return two output arguments that is the height in meters (m) and mass in kilograms (kg). Determine in SI units the height and mass of a 5 ft.15 in. person who weight 180 lb. Determine your own height and weight in SI units. Note: 1 meter = 39.3701 inch, 1 foot = 12 inches,...
Write a function int strlen(char s1[]) which returns the length of the char array s1.
Write a function int strlen(char s1[]) which returns the length of the char array s1.
4. Define the width of a rectangle as the longest length of its sides. Given a...
4. Define the width of a rectangle as the longest length of its sides. Given a closed rectangle A in Rn and a partition P of A, define the mesh of P as the maximum width of its subrectangles. Prove that a bounded function f : A → R is integrable on A if and only if, for every > 0, there is a δ > 0 such that U(f, P) − L(f, P) < for every partition P of...
Give a recurrence relation to find the length of the longest monotonically increasing subsequent of a...
Give a recurrence relation to find the length of the longest monotonically increasing subsequent of a array. Give the recursive algorithm based on the recurrence relation and explain the time complexity of this algorithm.
Complete the function, MycountWords in C++, which will count the number of words in a string....
Complete the function, MycountWords in C++, which will count the number of words in a string. We will have different word separators(such as newline(\n), spaces, special symbols(? | \ , . : ;) ) That will separate the words in the giving istringstream. Remember if a words is separated by a hyphen and followed by a new line, they're still one word. The function has an option to be sensitive to case and also avoid duplicates. for duplicates, this is...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT