daily-coding-problem icon indicating copy to clipboard operation
daily-coding-problem copied to clipboard

QNo 36 Query

Open BismeetSingh opened this issue 6 years ago • 0 comments

class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key

def createTree(arr):
    if not arr:
        return None
    mid = len(arr)//2
    node = Node(arr[mid])
    node.left = createTree(arr[:mid])
    node.right = createTree(arr[mid+1:])
    return node


def findSecondHighest(root):
    if root:
        global max, smax
        current = root.val
        if current > max:
            max, smax = current, max
        elif current < max and current > smax:
            smax = current
        findSecondHighest(root.left)
        findSecondHighest(root.right)


sorted_nums = [1, 2, 3, 4, 15, 6, 17, 8]
tree = createTree(sorted_nums)
smax = tree.val
max = tree.val
findSecondHighest(tree)
print(smax)

This works, but could you advise on how could I do better, or at least how could I avoid those global variables.

BismeetSingh avatar Dec 26 '19 13:12 BismeetSingh