コード例 #1
0
def test_pre_order():
    tree = BST(3)
    tree.add(1)
    tree.add(4)
    actual = tree.print_tree("pre_order")
    expected = '3-1-4-'
    assert actual == expected
コード例 #2
0
ファイル: test.py プロジェクト: mcqueenjordan/learning
def main():
    randints = [random.randint(0, 1000) for _ in range(50)]
    intkeys = set(randints)
    nodes = []
    for key in intkeys:
        nodes.append(Node(key))

    bst = BST()
    bst.build(nodes)
    bst.in_order_traversal()
コード例 #3
0
def main():
    global vis
    default_tree = [5, 6, 1, 2, 5, 8, 3, 10, 12, 13, 15]
    default_tree_two = [5, 4, 3, 2, 1, 6, 7, 8, 9, 10]

    tree = BST()
    [tree.insert(node) for node in default_tree]

    print "{:11s}: {}".format("Traversal", "Sequence")
    print "-" * 45
    run = lambda f, root: globals()[f](root)
    for traversal in traversals:
        run(traversal, tree.root)
        print "{:11s}: {}".format(traversal, ', '.join([str(x) for x in vis]))
        vis = []
コード例 #4
0
 def solution(self, answerList):
     if (answerList == None):
         return
     else:
         middle = answerList[len(answerList) // 2]
         left = answerList[:len(answerList) // 2]
         right = answerList[(len(answerList) // 2) + 1:]
         obj = BST()
         obj.addNode(obj.root, middle)
         for l in left:
             obj.addNode(obj.root, l)
         for r in right:
             obj.addNode(obj.root, r)
         # obj.inOrder(obj.root)
         # print("Height of tree:",obj.getHeightOfTree(obj.root))
         return obj
コード例 #5
0
def keyNodeInT1(root, key):
    if root == None:
        return None

    left = keyNodeInT1(root.left, key)
    right = keyNodeInT1(root.right, key)

    if (left != None):
        if (left.data == key):
            return left

    if (right != None):
        if (right.data == key):
            return right

    return root


if __name__ == '__main__':
    createtree = BST()
    nodes = [10, 5, 30, 4, 25, 35, 1, 20, 23, 32, 40, 0, 2]
    node1 = [1, 0, 2]
    createSubtree = BST()
    for n in node1:
        createSubtree.addNode(createSubtree.root, n)
    for n in nodes:
        createtree.addNode(createtree.root, n)
    # createtree.inOrder(createtree.root)
    keyNode = keyNodeInT1(createtree.root, 1)  # return closest node
    print("keynode found: ", keyNode.data)
    print(checkSubTree(keyNode, createSubtree.root))
コード例 #6
0
        leftSequence = leftSequence.getNext()


def weaveLists(left, right, results, prefix):
    if (len(left) == 0):
        result = prefix.copy()
        result.append(left)
        results.append(result)
        return
    else:
        result = prefix.copy()
        result.append(right)
        results.append(result)
        return

    headFirst = left.removeFirst()
    weaveLists(left, right, results, prefix)
    prefix.removeLast()
    left.addFirst(headFirst)

    headsecond = right.removeFirst()
    weaveLists(right, right, results, prefix)
    prefix.removeLast()
    right.addFirst(headsecond)


if __name__ == '__main__':
    treeObj = BST()
    numberList = [50, 30, 100, 20, 35, 200, 40, 150]
    for number in numberList:
        treeObj.addNode(treeObj.root, number)
コード例 #7
0
from tree import BST
from tree import Node

print(
    "Please enter the relative route to the text file you would like to analyze."
)
path = raw_input("> ")

tree = BST()

with open(path, "r") as input_file:  #open file
    for i, line in enumerate(input_file):  # loop through every line
        line = line.replace('.', '')  #make every word delimator a space
        line = line.replace(',', '')
        line = line.replace('?', '')
        line = line.replace('\n', '')

        if line[0] != "#":
            words = line.split(" ")  #split on spaces
            for word in words:  #\ #for every word
                if not word[0] in [
                        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
                ]:
                    word = word[:10]  #only keep first ten letters
                    tree.insert({
                        "word": word,
                        "lines": [i + 1]
                    })  #insert into tree

tree.display()
# tree.output()
コード例 #8
0
    if (root == None):
        return root
    if (root.data == target1 or root.data == target2):
        return root
    leftPath = recursiveOptimalSolution(root.left, target1, target2)
    rightPath = recursiveOptimalSolution(root.right, target1, target2)

    if (leftPath == None):
        return rightPath
    if (rightPath == None):
        return leftPath
    return root


if __name__ == '__main__':
    treeObj = BST()
    numberList = [10, 5, 20, 19, 25]
    for number in numberList:
        treeObj.addNode(treeObj.root, number)
    newTreeRoot = solution(treeObj.root)
    print('Special Tree')
    treeObj.inOrder(newTreeRoot)
    target1 = findNode(newTreeRoot, 19)
    target2 = findNode(newTreeRoot, 25)
    if (target1 == None):
        print("key 1 is not found")
        exit()
    if (target2 == None):
        print("Key 2 is not found")
        exit()
    ancestor = firstAncestor(target1, target2)
コード例 #9
0
ファイル: main.py プロジェクト: iashreya/Algorithms
from tree import BST

tree = BST()
tree.insert(9)
tree.insert(4)
tree.insert(6)
tree.insert(20)
tree.insert(170)
tree.insert(15)
tree.insert(1)
tree.insert(7)
tree.insert(10)

tree.traverse(tree.root)
コード例 #10
0
def test_breadth_first_bst():
    tree = BST(7)
    tree.add(4)
    tree.add(3)
    tree.add(2)
    tree.add(5)
    tree.add(9)
    tree.add(10)
    assert tree.print_tree('breadth_first') == '7-4-9-3-5-10-2-'
コード例 #11
0
def test_post_order():
    tree = BST(7)
    tree.add(4)
    tree.add(3)
    tree.add(2)
    tree.add(5)
    tree.add(9)
    tree.add(10)
    assert tree.print_tree('post_order') == '2-3-5-4-10-9-7-'
コード例 #12
0
def test_in_order():
    tree = BST(7)
    tree.add(4)
    tree.add(3)
    tree.add(2)
    tree.add(5)
    tree.add(9)
    tree.add(10)
    assert tree.print_tree('in_order') == '2-3-4-5-7-9-10-'
コード例 #13
0
ファイル: checkBalanced.py プロジェクト: ROHROCK/practice
    if (root == None):
        return -1

    left = getHeight(root.left)

    if (left == float('-inf')):
        return float('-inf')

    right = getHeight(root.right)
    if (right == float('-inf')):
        return float('-inf')

    if (abs(left - right) > 1):
        return float('-inf')
    else:
        return max(left, right) + 1


def checkBalanced(root):
    print(getHeight(root))
    return getHeight(root) != float('-inf')


if __name__ == '__main__':
    createTree = BST()

    elements = [4, 6, 5, 3, 2, 9, 1]
    for e in elements:
        createTree.addNode(createTree.root, e)
    # tree = createTree.solution([1,2,3,4,6,5])
    print(checkBalanced(createTree.root))
コード例 #14
0
ファイル: driver.py プロジェクト: trivedip/Basic-Algorithms
import random
from linkedlist import LinkedList
from tree import BST

a = LinkedList(5)
for _ in range(10):
    a.append(random.randint(0, 50))

# a.print()

b = BST(5)

b.append(10)
for _ in range(5):
    b.append(random.randint(0, 100))
b.pr()
コード例 #15
0
from tree import BST
tree = BST()
tree.insert(5)
tree.insert(4)
tree.insert(6)
tree.insert(10)
tree.insert(9)
tree.insert(11)

#tree.find(5)
tree.delete_value(5)
tree.printBST()
in_array = BST.inorder(tree.root)
print(in_array)

tree2 = BST()
tree2.insert(10)
tree2.insert(8)
tree2.insert(7)
tree2.insert(6)
tree2.insert(5)

in_array = BST.inorder(tree2.root)
print(in_array)
bTreeRoot = BST.getBalancedBST(in_array, 0, len(in_array) - 1)
pre_array = BST.preorder(bTreeRoot)
print(pre_array)
print(bTreeRoot.value)  # 7
myBalancedBST = BST()
myBalancedBST.root = bTreeRoot  # now is saved as proper tree