Пример #1
0
def sortedArrayToBST(arr):
    if not arr:
        return None
    mid = len(arr) // 2
    root = TreeNode(arr[mid])
    root.left = sortedArrayToBST(arr[:mid])
    root.right = sortedArrayToBST(arr[mid + 1:])
    return root
Пример #2
0
def sorted_array_to_bst(array):
    if len(array) == 0:
        return None
    elif len(array) == 1:
        return TreeNode(array[0])
    else:
        mid = int(len(array) / 2)
        root = TreeNode(array[mid])
        root.left = sorted_array_to_bst(array[:mid])
        root.right = sorted_array_to_bst(array[mid + 1:])
        return root
Пример #3
0
 def insert(self, root, value):
     if root == None:
         return
     else:
         if root.val > value:
             if root.left == None:
                 root.left = TreeNode(value)
             else:
                 self.insert(root.left, value)
         else:
             if root.right == None:
                 root.right = TreeNode(value)
             else:
                 self.insert(root.right, value)
Пример #4
0
def construct(inorder, preorder):
    if len(inorder) == 0 or len(preorder) == 0:
        return None
    else:
        root = preorder[0]
        index = inorder.index(root)
        left_inorder = inorder[:index]
        right_inorder = inorder[index + 1:]
        left_preorder = preorder[1:1 + len(left_inorder)]
        right_preorder = preorder[1 + len(left_inorder):]
        root = TreeNode(root)
        root.left = construct(left_inorder, left_preorder)
        root.right = construct(right_inorder, right_preorder)
        return root
def min_tree(arr):
    # base case
    if len(arr) is 0:
        return None

    # make node from middle of array
    mid = len(arr) / 2
    node = TreeNode(arr[mid])

    # recursively make node from each middle of each half of each array
    node.left = min_tree(arr[:mid])
    node.right = min_tree(arr[mid + 1:])  # +1 to not include current mid

    # returns root
    return node
Пример #6
0
def search(queue, method, initial_game):
    root = TreeNode(initial_game, None, None, 0, 0, 0)

    if method == 'astar' or method == 'best':
        queue.put((0, root))
    else:
        queue.put(root)

    visited_states = set()
    start = time.time()

    while (not queue.empty()) and (time.time() - start <= 300):
        if method == 'astar' or method == 'best':
            curr_f, current = queue.get()
        else:
            current = queue.get()

        if current.is_goal():
            return current

        # If the state of the game has already been visited, then continue
        if str(current.game) in visited_states:
            continue

        current.find_children(method)
        visited_states.add(str(current.game))

        for child in current.children:
            if method == 'depth' or method == 'breadth':
                queue.put(child)
            elif method == 'astar' or method == 'best':
                queue.put((child.f, child))
            print(child.game)
        print("===============================")
    return None
Пример #7
0
def monte_carlo_tree_search(board, pre_pos):
    root = TreeNode(board=board, pre_pos=pre_pos)  # 根结点,根结点无父亲
    for i in range(
            mcts_times
    ):  # 相当于(while resources_left(time, computational power):)即资源限制
        leaf = traverse(root)  # 选择和扩展,leaf = unvisited node(遍历根结点)
        simulation_result = rollout(leaf)  # 模拟
        backpropagate(leaf, simulation_result)  # 反向传播
    return best_child(root).pre_pos
Пример #8
0
def insert(tree, dataval):
    if tree.root is None:
        tree.root = TreeNode(dataval)
    else:
        pointer1 = tree.root

        while pointer1 is not None:
            if pointer1.dataval > dataval:
                if pointer1.leftchild is None:
                    pointer1.leftchild = TreeNode(dataval)
                    return
                else:
                    pointer1 = pointer1.leftchild
            elif pointer1.dataval < dataval:
                if pointer1.rightchild is None:
                    pointer1.rightchild = TreeNode(dataval)
                    return
                else:
                    pointer1 = pointer1.rightchild
            else:
                pointer1.duplicates += 1
                return
Пример #9
0
    def insert(self, key: int):
        if self.root is None:
            self.root = TreeNode(key)
            return

        parent = self.root
        if parent.key == key:
            raise KeyError("Repeated key")
        child = parent.left if key < parent.key else parent.right

        while child is not None:
            parent = child
            if parent.key == key:
                raise KeyError("Repeated key")
            child = child.left if key < child.key else child.right

        newNode = TreeNode(key)
        newNode.parent = parent

        if newNode.key < parent.key:
            parent.left = newNode
        else:
            parent.right = newNode
    def tree_insert(self, z: TreeNode):
        y = None
        x = self.head
        while x:
            y = x
            x = x.left if z.value < x.value else x.right

        z.parent = y

        if not y:
            self.head = z

        elif z.value < y.value:
            y.left = z

        else:
            y.right = z
    def transplant(self, u: TreeNode, v: TreeNode):
        """

            NB: transplant() doesn't attempt to update v.left and v.right
                doing so, or not doing so, is the responsibility of transplant()'s caller
        :param u:
        :param v:
        :return:
        """
        if not u.parent:
            self.head = v

        elif u == u.parent.left:
            u.parent.left = v

        else:
            u.parent.right = v

        if not v:
            v.parent = u.parent
Пример #12
0
# rType- TreeNode
# input - TreeNode
def successor(root):
    if root.right:
        return minValue(root.right)
    parent = root.parent
    while parent:
        if root != parent.right:
            break
        root = parent
        parent = parent.parent
    return parent


if __name__ == "__main__":
    twenty = TreeNode(20)
    eight = TreeNode(20)
    four = TreeNode(4)
    twelve = TreeNode(12)
    ten = TreeNode(10)
    fourteen = TreeNode(14)
    twentytwo = TreeNode(22)
    # setting Parents
    eight.parent = twenty
    four.parent = eight
    twelve.parent = eight
    ten.parent = twelve
    fourteen.parent = twelve
    twentytwo.parent = twenty
    # left right
    twenty.right = twentytwo
Пример #13
0
 def addNode(self, label):
     if label not in self.nodes:
         self.nodes[label] = TreeNode(label)
     return self.nodes[label]
Пример #14
0
Validate BST: Implement a function to check if a binary tree is a binary search tree.
'''

from Node import TreeNode, preOrderTraversal, postOrderTraversal, inOrderTraversal

# recent keeps track of the last value compared


def validBST(root, recent):
    if not root:
        return True
    if not (validBST(root.left, recent)):
        return False
    if recent is not None and root.value <= recent:
        return False
    recent = root.value
    if not (validBST(root.right, recent)):
        return False
    return True


if __name__ == "__main__":
    one = TreeNode(1)
    two = TreeNode(2)
    three = TreeNode(3)
    four = TreeNode(4)
    five = TreeNode(5)
    six = TreeNode(6)
    seven = TreeNode(7)
    eight = TreeNode(8)
    print(validBST(one, None))
    # left & right heights
    left_height = root.height(root.left)
    right_height = root.height(root.right)

    # get positive value of difference in height
    height_difference = abs(left_height - right_height)

    # check height requirement satisfied
    if height_difference <= 1:
        # ... recursively
        if check_balanced(root.left) is True and check_balanced(
                root.right) is True:
            return True

    # if we reach here means tree is not
    # height-balanced tree
    return False


if __name__ == "__main__":
    bal_root = min_tree([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
    print(check_balanced(bal_root))

    unbal_root = TreeNode(5)
    unbal_root.left = TreeNode(4)
    unbal_root.left.left = TreeNode(3)
    unbal_root.left.left.left = TreeNode(2)
    unbal_root.left.left.left.left = TreeNode(1)
    unbal_root.right = TreeNode(6)
    print(check_balanced(unbal_root))
Пример #16
0
        return checkSubtree(r1.left, r2) or checkSubtree(r1.right, r2)


def sameTree(r1, r2):
    if not r1 and not r2:
        return True
    elif not r1 or not r2:
        return False
    elif r1.value != r2.value:
        return False
    else:
        return sameTree(r1.left, r2.left) and sameTree(r1.right, r2.right)


if __name__ == "__main__":
    one = TreeNode(1)
    two = TreeNode(2)
    three = TreeNode(3)
    four = TreeNode(4)
    five = TreeNode(5)
    six = TreeNode(6)
    seven = TreeNode(7)
    eight = TreeNode(8)
    one.left = two
    one.right = three
    two.left = four
    two.right = five
    three.left = six
    three.right = seven
    r1 = one
    newOne = TreeNode(2)
Пример #17
0
            return result
        prefix = []
        prefix.append(node.value)
        leftSeq = self.allSequences(node.left)
        rightSeq = self.allSequences(node.right)
        for first in leftSeq:
            for second in rightSeq:
                weaved = []
                self.weavedLists(first, second, weaved, prefix)
                for item in weaved:
                    result.append(item)
        return result


if __name__ == "__main__":
    fifty = TreeNode(50)
    twenty = TreeNode(20)
    sixty = TreeNode(60)
    ten = TreeNode(10)
    twentyFive = TreeNode(25)
    seventy = TreeNode(70)
    five = TreeNode(5)
    fifteen = TreeNode(15)
    sixtyFive = TreeNode(65)
    eighty = TreeNode(80)
    fifty.left = twenty
    fifty.right = sixty
    twenty.left = ten
    twenty.right = twentyFive
    sixty.right = seventy
    ten.left = five
Пример #18
0
 def append(self, value):
     newNode = TreeNode(value)
     self.placeNode(newNode, self.root)
Пример #19
0
 def __init__(self, value):
     self.setRoot(TreeNode(value))
Пример #20
0
from Node import TreeNode

def preorder_traversal(n):
	if n == None:
		return 
	else:
		print(n.val, end=" ")
		preorder_traversal(n.left)
		preorder_traversal(n.right)		
		
def preorder_traversal_iterative(n):
	stack = [n]
	while(len(stack) != 0):
		node = stack.pop()
		if node.is_visited:
			print(node.val, end=" ")
		else:	
			if node.right != None:
				stack.append(node.right)
			if node.left != None:
				stack.append(node.left)				
			node.is_visited = True				
			stack.append(node)			
		
n = TreeNode.get_sample()
preorder_traversal(n)
print()
preorder_traversal_iterative(n)
Пример #21
0
                childNode = parentNode.left
            else:
                childNode = parentNode.right
            stack.pop()
            stack.append((parentNode, parentState - 1))
            if childNode:
                stack.append((childNode, bothPending))
        else:
            if oneNodeFound and len(stack) - 1 == fcaIndex:
                fcaIndex -= 1
            stack.pop()
    return None


if __name__ == "__main__":
    one = TreeNode(1)
    two = TreeNode(2)
    three = TreeNode(3)
    four = TreeNode(4)
    five = TreeNode(5)
    six = TreeNode(6)
    seven = TreeNode(7)
    eight = TreeNode(8)
    nine = TreeNode(9)
    one.left = two
    one.right = three
    two.left = four
    two.right = five
    three.left = six
    three.right = seven
    four.left = eight
Пример #22
0
def isValidBST(root, max_val, min_val):
    if root == None:
        return True
    else:
        if root.val > max_val or root.val < min_val:
            return False
        else:
            if (root.left != None and root.val < root.left.val) or (
                    root.right != None and root.val > root.right.val):
                return False
            else:
                return isValidBST(root.left, root.val, min_val) and isValidBST(
                    root.right, max_val, root.val)


head = TreeNode.get_sample()
print(isValidBST(head, sys.maxsize, -sys.maxsize - 1))

n1 = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n4 = TreeNode(4)
n5 = TreeNode(5)
n6 = TreeNode(6)
n7 = TreeNode(7)

n4.left = n2
n4.right = n5
n2.right = n3
n2.left = n1
n5.right = n6