Search
 
SCRIPT & CODE EXAMPLE
 

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
Comment

python tree

class TreeNode:
    def __init__(self, data):
        self.data = data
        self.children = []
        self.parent = None

    def add_child(self, child):
        child.parent = self
        self.children.append(child)

    def print_tree(self):
        print(self.data)
        if self.children:
            for child in self.children:
                child.print_tree()

    def get_level(self):
        level = 0
        p = self.parent
        while p:
            level += 1
            p = p.parent
        return level


def build_product_tree():
    root = TreeNode('Electronics')

    laptop = TreeNode('Laptop')
    laptop.add_child(TreeNode('Thinkpad'))
    laptop.add_child(TreeNode('Surface'))
    laptop.add_child(TreeNode('Mac'))

    cellphone = TreeNode('Cellphone')
    cellphone.add_child(TreeNode('iphone'))
    cellphone.add_child(TreeNode('google pixel'))
    cellphone.add_child(TreeNode('vivo'))

    tv = TreeNode('Television')
    tv.add_child(TreeNode('samsung'))
    tv.add_child(TreeNode('lg'))

    root.add_child(laptop)
    root.add_child(cellphone)
    root.add_child(tv)

    root.print_tree()
Comment

tree implementation in python

class Tree:
  def __init__(self, val = None):
    if val != None:
	    self.val = val
    else:
        self.val = None
    self.left = None
    self.right = None

  def insert(self, val):
    if self.val:
        if val < self.val:
            if self.left is None:
            	self.left = Tree(val)
            else:
            	self.left.insert(val)
        elif val > self.val:
        		if self.right is None:
              self.right = Tree(val)
            else:
              self.right.insert(val)
    else:
        self.val = val

  def printValues(self):
    if self.left:
        self.left.printValues()
    print(self.val)
    if self.right:
        self.right.printValues()

tree = Tree(20)
tree.left = Tree(18)
tree.right = Tree(22)
tree.insert(19)
tree.insert(24)
tree.insert(5)
tree.insert(21)

tree.printValues()
Comment

Tree in python

class Node:
     def __init__(self,data):
          self.data = data
          self.parent = None
          self.left = None
          self.right = None

     def __repr__(self):
          return repr(self.data)

     def add_left(self,node):
         self.left = node
         if node is not None:
             node.parent = self

     def add_right(self,node):
         self.right = node
         if node is not None:
             node.parent = self
'''
Example:
          _2_
        /       
       7         9
      /          
     1   6         8
         /        / 
       5   10   3   4
'''
def create_tree():
    two = Node(2)
    seven = Node(7)
    nine = Node(9)
    two.add_left(seven)
    two.add_right(nine)
    one = Node(1)
    six = Node(6)
    seven.add_left(one)
    seven.add_right(six)
    five = Node(5)
    ten = Node(10)
    six.add_left(five)
    six.add_right(ten)
    eight = Node(8)
    three = Node(3)
    four = Node(4)
    nine.add_right(eight)
    eight.add_left(three)
    eight.add_right(four)

    # now return the root node
    return two

def pre_order(node):
    print(node)
    if node.left:
        pre_order(node.left)
    if node.right:
        pre_order(node.right)

def in_order(node):
    if node.left:
        in_order(node.left)
    print(node)
    if node.right:
        in_order(node.right)

def post_order(node):
    if node.left:
        post_order(node.left)
    if node.right:
        post_order(node.right)
    print(node)

if __name__ == "__main__":
    root = create_tree()
    print("
Pre-order traversal:")
    pre_order(root)
    print("
In-order traversal:")
    in_order(root)
    print("
Post-order traversal:")
    post_order(root)
Comment

python tree library

# pypi, the Python Package Index, suggests tinytree, treedict, caxes, 
# treelib, pyavl... these are just the top few after filtering away the 
# many accidental hits (which point to specific tree such as XML ones, 
#                 AST ones, etc, etc;-). If you clarify what you want 
# to do with your trees it may be easier to suggest a specific package.

pip install treelib pyavl tinytree treedict caxes
# or 
pip3 install treelib pyavl tinytree treedict caxes
Comment

PREVIOUS NEXT
Code Example
Python :: split coumn of df into multiple dynamic columns 
Python :: python glob subdirectories 
Python :: python try catch print stack 
Python :: move files in python 
Python :: Python Changing a Tuple 
Python :: how to get session value in django template 
Python :: import matplotlib pyplot as plt 
Python :: how to set the size of a kivy window bigger than screen 
Python :: intersection of three arrays 
Python :: array in python 
Python :: discord.py read custom status 
Python :: python not in list 
Python :: ValueError: `logits` and `labels` must have the same shape, received ((None, 10) vs (None, 1)). 
Python :: get height of image in pygame 
Python :: change time format pm am in python 
Python :: decision tree python 
Python :: python create a set of class 
Python :: python tkinter menu widget 
Python :: try for loop python 
Python :: python filter numbers from list 
Python :: python strptime milliseconds 
Python :: python merge two list 
Python :: what is iteration in python 
Python :: NumPy flip Syntax 
Python :: how to calculate log 10 in python 
Python :: PHP echo multi lines Using Nowdoc variable 
Python :: lose your django secret key 
Python :: python dictionary contains key 
Python :: python gitignore 
Python :: values missing comparing datasets 
ADD CONTENT
Topic
Content
Source link
Name
2+3 =