Untitled

mail@pastecode.io avatar
unknown
python
a year ago
903 B
0
Indexable
Never
class Node:
    def __init__(self, val: int = None) -> None:
        self.val = val
        self.left = self.right = None

class Tree:
    def __init__(self) -> None:
        self.root = None

    def insert(self, newVal: int):
        if not self.root:
            self.root = Node(newVal)
        else:
            prev = None
            cur = self.root

            while (cur):
                prev = cur
                if newVal < cur.val:
                    cur = cur.left
                else:
                    cur = cur.right
                
            if newVal < prev.val:
                prev.left = Node(newVal)
            else:
                prev.right = Node(newVal)
    
    def printTree(self, root: Node):
        if not root:
            return
        else:
            self.printTree(root.left)
            print(root.val, end = ' ')
            self.printTree(root.right)