Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

tree python

import random
class Node:
    def __init__(self, v, dx=None, sx=None):
        self.dx = dx
        self.sx = sx
        self.v = v

    def nodeCount(self):
        if self is None:
            return 0
        x, y = 0, 0
        if self.sx:
            x = self.sx.nodeCount()
        if self.dx:
            y = self.dx.nodeCount()
        return x + y + 1

    def minValue(self):
        if self is None:
            return float("+inf")
        x = y = float("+inf")
        if self.sx:
            x = self.sx.minValue()
        if self.dx:
            y = self.dx.minValue()
        return min(self.v, x, y) 

    def maxValue(self):
        if self is None:
            return float("-inf")
        x = y = float("-inf")
        if self.sx:
            x = self.sx.maxValue()
        if self.dx:
            y = self.dx.maxValue()
        return max(self.v, x, y)

    def printNode(self):
        if self is None:
            return
        print(self.v)
        if self.sx:
            self.sx.printNode()
        if self.dx:
            self.dx.printNode()
    
class binaryTree:
    def __init__(self, Node=None):
        self.Node = Node

    def buildTree(self, numberOfNode, valueLimit):
        if numberOfNode == 0: 
            return None

        node = Node(random.randint(1, valueLimit))
        numberOfNode -= 1
        if numberOfNode >= 0:
            x = random.randint(0, numberOfNode)
            node.sx = self.buildTree(x, valueLimit)
            node.dx = self.buildTree(numberOfNode-x, valueLimit)

        return node
 
PREVIOUS NEXT
Tagged: #tree #python
ADD COMMENT
Topic
Name
8+9 =