In: Computer Science
Python:
Create two Binary Tree class methods that can return the maximum value within a Binary Tree and the minimum value within a Binary Tree.
Test the methods in your code
Example syntax to call these methods:
MyTree.Max()
MyTree.Min()
Please refer to the below python code for the above stated problem:
Please refer to the comments in the code snippet for better understanding.
# A class to create a new node 
class newNodeCreate: 
        def __init__(self, data): 
                self.data = data 
                self.left = self.right = None                 #defining the left and the right nodes of the root
        
# Returns maximum value in a  
def findMaxValue(root): 
        
        # Base case where the binary tree might be empty
        if (root == None): 
                return float('-inf') 
        # Return maximum of 3 values: 
        # 1) Root's value 2) Max in Left Subtree 
        # 3) Max in right subtree 
        rootdata = root.data 
        left1 = findMaxValue(root.left) 
        right1 = findMaxValue(root.right) 
        if (left1 > rootdata): 
                rootdata = left1 
        if (right1 > rootdata): 
                rootdata = right1 
        return rootdata
# Returns the min value in a binary tree 
def findMinValue(root): 
    if root is None:                # Base case where the binary tree might be empty
        return float('inf') 
  
    # Return minimum of 3 values: 
        # 1) Root's value 2) Min in Left Subtree 
        # 3) Min in right subtree 
    rootdata = root.data 
    left1 = findMinValue(root.left) 
    right1 = findMinValue(root.right) 
    if left1 < rootdata: 
        rootdata = left1 
    if right1 < rootdata: 
        rootdata = right1 
    return rootdata 
# Code to define the starting binary tree (Driver Code) and find the max and min values
if __name__ == '__main__':                                  # this defines the first piece of code that runs when we run the python module
        root = newNodeCreate(2) 
        root.left        = newNodeCreate(7) 
        root.right       = newNodeCreate(5) 
        root.left.right = newNodeCreate(6) 
        root.left.right.left=newNodeCreate(1) 
        root.left.right.right=newNodeCreate(11) 
        root.right.right=newNodeCreate(9) 
        root.right.right.left=newNodeCreate(4) 
        #testing the function findMaxValue the returned value should be 11 according to the above created tree
        print("Maximum element is", 
                                findMaxValue(root))
        #testing the function findMinValue the returned value should be 1 according to the above created tree
        print("Minimum element is", 
                                findMinValue(root))