Example #1
0
    def test_insert_no_left_child(self):
        node = Node(3, 'value')

        assert node.left_child is None
        assert node.insert(2, 'left_value') is True
        assert node.left_child is not None
        assert node.left_child.key == 2
        assert node.left_child.value == 'left_value'
 def sortedarraytoBSTrecu(self, nums, begin, end):
     if begin > end:
         return None
     mid = begin + (end - begin) // 2
     root = TN(nums[mid])
     root.left = self.sortedarraytoBSTrecu(nums, begin, mid - 1)
     root.right = self.sortedarraytoBSTrecu(nums, mid + 1, end)
     return root
Example #3
0
    def test_insert_no_right_child(self):
        node = Node(3, 'value')

        assert node.right_child is None
        assert node.insert(4, 'right_value') is True
        assert node.right_child is not None
        assert node.right_child.key == 4
        assert node.right_child.value == 'right_value'
Example #4
0
    def test_insert_right_child(self):
        node = Node(3, 'value')
        node.insert(4, 'right_value')

        assert node.right_child.right_child is None
        node.insert(5, 'right_child_value')
        assert node.right_child.right_child is not None
        assert node.right_child.right_child.key == 5
        assert node.right_child.right_child.value == 'right_child_value'
Example #5
0
    def test_insert_left_child(self):
        node = Node(3, 'value')
        node.insert(2, 'left_value')

        assert node.left_child.left_child is None
        node.insert(1, 'left_child_value')
        assert node.left_child.left_child is not None
        assert node.left_child.left_child.key == 1
        assert node.left_child.left_child.value == 'left_child_value'
Example #6
0
    def test_get_node_list(self):
        node = Node(4, 'a')
        node.insert(2, 'b')
        node.insert(5, 'c')
        node.insert(1, 'd')
        node.insert(3, 'e')
        node.insert(6, 'f')

        assert node.get_node_list(node) == [1, 2, 3, 4, 5, 6]
Example #7
0
 def __init__(self, val):
     Node.__init__(self, val)
     self.prob = Treap.gen_prob()
Example #8
0
 def helper(i):
     if i > (size-1):
         return None
     else:
         a = Node(l[i], helper(2*i +1), helper(2*i + 2))
     return a
Example #9
0
class Solution(object):

    def identical_trees(self, tree_1, tree_2):
        if tree_1 is None and tree_2 is None:
            return True

        if tree_1 is not None and tree_2 is not None:
            return ((tree_1.value == tree_2.value) and
                    self.identical_trees(tree_1.left, tree_2.left) and
                    self.identical_trees(tree_1.right, tree_2.right))

        return False

S = Solution()
root1 = Treenode(1)
root1.left = Treenode(2)
root1.right = Treenode(3)
root1.left.left = Treenode(4)
root1.left.right = Treenode(5)
print root1

root2 = Treenode(1)
root2.left = Treenode(2)
root2.right = Treenode(3)
root2.left.left = Treenode(4)
root2.left.right = Treenode(5)
print root2

if S.identical_trees(root1, root2):
    print "Trees are identical"
Example #10
0
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root: return []
        res = []
        cur_level = [root]
        depth = 0
        while cur_level:
            tmp = []
            next_level = []
            for node in cur_level:
                tmp.append(node.val)
                if node.left:
                    next_level.append(node.left)
                if node.right:
                    next_level.append(node.right)
            if depth % 2 == 1:
                res.append(tmp[::-1])
            else:
                res.append(tmp)
            depth += 1
            cur_level = next_level
        return res


if __name__ == "__main__":
    root = TreeNode(3)
    root.left = TreeNode(9)
    root.right = TreeNode(20)
    root.right.left = TreeNode(15)
    root.right.right = TreeNode(7)
    print(root)
    print(Solution().zigzagLevelOrder(root))
Example #11
0
 def mirrorTree(self, root: TreeNode) -> TreeNode:
     if not root:
         return
     root.left, root.right = self.mirrorTree(root.right), self.mirrorTree(
         root.left)
     return root
Example #12
0
"""
https://leetcode.com/problems/search-in-a-binary-search-tree/
"""
from binarytree import Node


class SearchInBST:
    def searchBST(self, root, val: int):
        if root == None or root.val == val:
            return root
        if val < root.val:
            return self.searchBST(root.left, val)
        else:
            return self.searchBST(root.right, val)


obj = SearchInBST()
root = Node(4)
root.left = Node(2)
root.right = Node(7)
root.left.left = Node(1)
root.left.right = Node(3)
print(obj.searchBST(root, 2))
Example #13
0
	def test_LCA(self):
		root = Node(5)
		root.left = Node(4)
		root.left.left = Node(2)
		root.left.right = Node(3)
		root.right = Node(6)
		root.right.left = Node(11)
		root.right.right = Node(7)
		root.right.right.left = Node(8)
		print(root)
		self.assertEqual(lcaPython.findLCA(root,3,7),5)
		self.assertEqual(lcaPython.findLCA(root,2,4),4)
		self.assertEqual(lcaPython.findLCA(root,6,3),5)
		self.assertEqual(lcaPython.findLCA(root,2,3),4)
		self.assertEqual(lcaPython.findLCA(root,5,6),5)
		self.assertEqual(lcaPython.findLCA(root,5,5),5)
		self.assertEqual(lcaPython.findLCA(root,7,7),7)
		self.assertEqual(lcaPython.findLCA(root,7,11),6)
		self.assertEqual(lcaPython.findLCA(root,7,20),-1)
Example #14
0
    async def bst(self, ctx: commands.Context):
        """
        `!bst` __`Binary Search Tree analysis tool`__
        **Usage:** !bst <node> [node] [...]
        **Examples:**
        `!bst 2 1 3` displays a BST in ASCII and PNG form with root node 2 and leaves 1, 3
        `!bst 4 5 6` displays a BST in ASCII and PNG form with root node 4, parent node 5 and leaf 6

        Launching the command activates a 60 second window during which additional unprefixed commands can be called:

        `pre`        displays pre-order traversal of the tree
        `in`         displays in-order traversal of the tree
        `level`      displays level-order traversal of the tree
        `post`       displays post-order traversal of the tree
        `about`      displays characteristics of the tree
        `pause`      stops the 60 second countdown timer
        `unpause`    starts the 60 second countdown timer
        `show`       displays the ASCII and PNG representations of the tree again
        `exit`       exits the window

        `insert <node> [node] [...]` inserts nodes into the tree
        **Example:** `insert 5 7 6`  inserts nodes 5, 7 and 6, in that order

        `delete <node> [node] [...]` deletes nodes from the tree
        **Example:** `delete 7 8 9`  deletes nodes 7, 8 and 9, in that order
        """

        numbers = []

        for num in ctx.message.content[5:].replace(",", "").split():
            if re.fullmatch(r"[+-]?((\d+(\.\d*)?)|(\.\d+))", num):
                try:
                    numbers.append(int(num))
                except ValueError:
                    numbers.append(float(num))
            else:
                raise BadArgs("Please provide valid numbers for the tree.")

        if not numbers:
            raise BadArgs("Please provide some numbers for the tree.", show_help=True)

        root = Node(numbers[0])

        nodes = [root]

        def insert(subroot: Node, num: int) -> None:
            if num < subroot.val:
                if not subroot.left:
                    node = Node(num)
                    subroot.left = node
                    nodes.append(node)
                else:
                    insert(subroot.left, num)
            else:
                if not subroot.right:
                    node = Node(num)
                    subroot.right = node
                    nodes.append(node)
                else:
                    insert(subroot.right, num)

        def delete(subroot: Node, num: int) -> Node:
            if subroot:
                if subroot.val == num:
                    if subroot.left is not None and subroot.right is not None:
                        parent = subroot
                        predecessor = subroot.left

                        while predecessor.right is not None:
                            parent = predecessor
                            predecessor = predecessor.right

                        if parent.right == predecessor:
                            parent.right = predecessor.left
                        else:
                            parent.left = predecessor.left

                        predecessor.left = subroot.left
                        predecessor.right = subroot.right

                        ret = predecessor
                    else:
                        if subroot.left is not None:
                            ret = subroot.left
                        else:
                            ret = subroot.right

                    nodes.remove(subroot)
                    del subroot
                    return ret
                else:
                    if subroot.val > num:
                        if subroot.left:
                            subroot.left = delete(subroot.left, num)
                    else:
                        if subroot.right:
                            subroot.right = delete(subroot.right, num)

            return subroot

        def get_node(num: int) -> Optional[Node]:
            for node in nodes:
                if node.val == num:
                    return node

            return None

        for num in numbers[1:]:
            if not get_node(num):
                insert(root, num)

        timeout = 60
        display = True

        def draw_bst(root: Node) -> None:
            graph = root.graphviz()
            graph.render("bst", format="png")

        while True:
            draw_bst(root)
            text = f"```{root}\n```"

            if display:
                await ctx.send(text, file=discord.File("bst.png"))
                display = False

            try:
                message = await self.bot.wait_for("message", timeout=timeout, check=lambda m: m.channel.id == ctx.channel.id and m.author.id == ctx.author.id)
            except asyncio.exceptions.TimeoutError:
                for f in glob.glob("bst*"):
                    os.remove(f)

                return await ctx.send("Timed out.", delete_after=5)

            command = message.content.replace(",", "").replace("!", "").lower()

            if command.startswith("level"):
                await ctx.send("Level-Order Traversal:\n**" + "  ".join([str(n.val) for n in root.levelorder]) + "**")
            elif command.startswith("pre"):
                await ctx.send("Pre-Order Traversal:\n**" + "  ".join([str(n.val) for n in root.preorder]) + "**")
            elif command.startswith("post"):
                await ctx.send("Post-Order Traversal:\n**" + "  ".join([str(n.val) for n in root.postorder]) + "**")
            elif command.startswith("in") and not command.startswith("ins"):
                await ctx.send("In-Order Traversal:\n**" + "  ".join([str(n.val) for n in root.inorder]) + "**")
            elif command.startswith("about"):
                embed = discord.Embed(title="Binary Search Tree Info", description="> " + text.replace("\n", "\n> "), color=random.randint(0, 0xffffff))
                embed.add_field(name="Height:", value=str(root.height))
                embed.add_field(name="Balanced?", value=str(root.is_balanced))
                embed.add_field(name="Complete?", value=str(root.is_complete))
                embed.add_field(name="Full?", value=str(root.is_strict))
                embed.add_field(name="Perfect?", value=str(root.is_perfect))
                embed.add_field(name="Number of leaves:", value=str(root.leaf_count))
                embed.add_field(name="Max Leaf Depth:", value=str(root.max_leaf_depth))
                embed.add_field(name="Min Leaf Depth:", value=str(root.min_leaf_depth))
                embed.add_field(name="Max Node Value:", value=str(root.max_node_value))
                embed.add_field(name="Min Node Value:", value=str(root.min_node_value))
                embed.add_field(name="Entries:", value=str(root.size))
                embed.add_field(name="Pre-Order Traversal:", value=" ".join([str(n.val) for n in root.preorder]))
                embed.add_field(name="In-Order Traversal:", value=" ".join([str(n.val) for n in root.inorder]))
                embed.add_field(name="Level-Order Traversal:", value=" ".join([str(n.val) for n in root.levelorder]))
                embed.add_field(name="Post-Order Traversal:", value=" ".join([str(n.val) for n in root.postorder]))

                if root.left:
                    embed.add_field(name="In-Order Predecessor:", value=str(max(filter(lambda x: x is not None, root.left.values))))

                if root.right:
                    embed.add_field(name="In-Order Successor:", value=str(min(filter(lambda x: x is not None, root.right.values))))

                await ctx.send(embed=embed, file=discord.File("bst.png"))
            elif command.startswith("pause"):
                timeout = 86400
                await ctx.send("Timeout paused.")
            elif command.startswith("unpause"):
                timeout = 60
                await ctx.send("Timeout reset to 60 seconds.")
            elif command.startswith("show"):
                display = True
            elif command.startswith("insert"):
                add = []

                for entry in command[7:].split():
                    if re.fullmatch(r"[+-]?((\d+(\.\d*)?)|(\.\d+))", entry):
                        try:
                            num = int(entry)
                        except ValueError:
                            num = float(entry)
                    else:
                        continue

                    add.append(str(num))

                    if not get_node(num):
                        insert(root, num)

                await ctx.send(f"Inserted {','.join(add)}.")
                display = True
            elif command.startswith("delete"):
                remove = []

                for entry in command[7:].split():
                    try:
                        num = float(entry)
                    except ValueError:
                        continue

                    if root.size == 1:
                        await ctx.send("Tree has reached one node in size. Stopping deletions.")
                        break

                    if math.modf(num)[0] == 0:
                        num = int(round(num))

                    if not get_node(num):
                        continue

                    remove.append(str(num))
                    root = delete(root, num)

                await ctx.send(f"Deleted {','.join(remove)}.")
                display = True
            elif command.startswith("exit"):
                for f in glob.glob("bst*"):
                    os.remove(f)

                return await ctx.send("Exiting.")
            elif command.startswith("bst"):
                return
Example #15
0
    def display(self, msg):
        print(msg)
        pprint(self.root)


if __name__ == "__main__":
    print("program to generate the AVL trees")
    N = int(input("How many numbers?"))
    lt = random.sample(range(1, 1000), N)
    print(lt)
    bt = BinarySearchTree()
    av = AVLTree()
    for i in range(N):
        #print("Inserting ... %d" %lt[i])
        bt.insert(Node(lt[i]))
        av.insert(AVLnode(lt[i]))
        #av.display("AVL tree at iteration %d" %i)
        #print(".........................")
        #print()

    bt.display("The input Binary Tree is as follows")
    av.display("The AVL tree is as follows")
    height = av.get_height()
    print("The height of the tree is %d" % height)
    while 1:
        item = int(input("Enter the node value to remove"))
        av.delete(item)
        av.display("The AVL tree afer the node removal")
        height = av.get_height()
        print("The height of the tree is %d" % height)
import random
from itertools import combinations,permutations
from binarytree import tree, Node

## to anaylze every cases, we use permutations of X to represent the order of
## these 6 value, the more previous, the more lower
## x2,x4,x1,x3,x5,x6 means x2<x4<x1<x3<x5<x6
X = ["x1","x2","x3","x4","x5","x6"]

state_list = [("",""),("x1","x2"),("x2","x1"),("x3","x4"),("x4","x3"),("x5","x6"),("x6","x5")]
## the search branch that player 1 moves on a, since we use the binarytree lib
## we build 3 subtrees for this branch depending on player 2's move
## s for swap. so three trees are ab,ac,as.
## Since the binarytree node's value must be number, so here we use a
## state_list for our node's value.
root_ab = Node(0)
root_ab.left = Node(1)
root_ab.right = Node(0)
root_ab.right.left = Node(2)
root_ab.right.right = Node(5)
# print(root_ab)
root_ac = Node(0)
root_ac.left = Node(3)
root_ac.right = Node(0)
root_ac.right.left = Node(4)
root_ac.right.right = Node(6)
# print(root_ac)
root_as = Node(0)
root_as.left = Node(2)
root_as.right = Node(4)
# print(root_as)
Example #17
0
 def draw_bst(root: Node) -> None:
     graph = root.graphviz()
     graph.render("bst", format="png")
Example #18
0
def pre_process_points(points):
    global stop_y
    global sls
    global intersection_discovered
    global intersection_point

    for i in xrange(len(points)):
        print "Coordinates = " + str(points[i].x) + "," + str(points[i].y)

    # Sort the points in the event queue by y-coordinate
    event_queue = sorted(points, key=lambda point: point.y)
    last_point = 0
    sls = None
    index = 0
    # Consider each point in the event queue
    for current_point in event_queue:
        stop_y = current_point.y - last_point
        # If the current point has a previous point, insert that line segment into the sls
        if current_point.prev_point is not None:
            line_segment_1 = LineSegment(current_point,
                                         current_point.prev_point,
                                         current_point.prev_point.index)
            line_segment_1_dup = LineSegment(current_point.prev_point,
                                             current_point,
                                             current_point.prev_point.index)
            if sls is None:
                sls = Node(line_segment_1)
                index = index + 1
            else:
                # Verify that line segment is not already present
                lsegment = sls.lookup(line_segment_1)
                rsegment = sls.lookup(line_segment_1_dup)
                if lsegment[0] is None and rsegment[0] is None:
                    sls.insert(line_segment_1)
                    index = index + 1
                    findPreSuc.pre = None
                    findPreSuc.suc = None
                    findPreSuc(sls, line_segment_1)

                    # Check for intersection with predecessor
                    if findPreSuc.pre is not None and abs(
                            findPreSuc.pre.data.index -
                            line_segment_1.index) > 1:
                        if do_intersect(findPreSuc.pre.data.start,
                                        findPreSuc.pre.data.end,
                                        line_segment_1.start,
                                        line_segment_1.end):
                            print "Predecessor is", findPreSuc.pre.data.label, "{(", \
                                findPreSuc.pre.data.start.x, ",", findPreSuc.pre.data.start.y, "),(", \
                                findPreSuc.pre.data.end.x, ",", findPreSuc.pre.data.end.y, ")}"
                            print "Current Point is", line_segment_1.label, "{(", \
                                line_segment_1.start.x, ",", line_segment_1.start.y, "),(", \
                                line_segment_1.end.x, ",", line_segment_1.end.y, ")}"
                            print "Intersection Discovered1"
                            intersection_discovered = True
                            intersection_point = get_intersection_point(
                                findPreSuc.pre.data, line_segment_1)
                            if automate_clicked:
                                if test is not None:
                                    sls_canvas.delete(test)
                                test = sls_canvas.create_text(
                                    window_width / 2,
                                    20,
                                    fill="darkblue",
                                    font="Times 20 italic bold",
                                    text="Intersection Discovered at (" +
                                    str(intersection_point.x) + ", " +
                                    str(intersection_point.y) + ")",
                                    anchor=CENTER)
                                child_canvas.create_oval(
                                    intersection_point.x - 2.0,
                                    intersection_point.y - 2.0,
                                    intersection_point.x + 2.0,
                                    intersection_point.y + 2.0,
                                    outline="red",
                                    fill="red",
                                    width=2)

                    # Check for intersection with successor
                    if findPreSuc.suc is not None and abs(
                            findPreSuc.suc.data.index -
                            line_segment_1.index) > 1:
                        if do_intersect(findPreSuc.suc.data.start,
                                        findPreSuc.suc.data.end,
                                        line_segment_1.start,
                                        line_segment_1.end):
                            print "Successor is", findPreSuc.suc.data.label, "{(", \
                                findPreSuc.suc.data.start.x, ",", findPreSuc.suc.data.start.y, "),(", \
                                findPreSuc.suc.data.end.x, ",", findPreSuc.suc.data.end.y, ")}"
                            print "Current Point is", line_segment_1.label, "{(", \
                                line_segment_1.start.x, ",", line_segment_1.start.y, "),(", \
                                line_segment_1.end.x, ",", line_segment_1.end.y, ")}"
                            print "Intersection Discovered2"
                            intersection_discovered = True
                            intersection_point = get_intersection_point(
                                findPreSuc.suc.data, line_segment_1)
                            if automate_clicked:
                                if test is not None:
                                    sls_canvas.delete(test)
                                test = sls_canvas.create_text(
                                    window_width / 2,
                                    20,
                                    fill="darkblue",
                                    font="Times 20 italic bold",
                                    text="Intersection Discovered at (" +
                                    str(intersection_point.x) + ", " +
                                    str(intersection_point.y) + ")",
                                    anchor=CENTER)
                                child_canvas.create_oval(
                                    intersection_point.x - 2.0,
                                    intersection_point.y - 2.0,
                                    intersection_point.x + 2.0,
                                    intersection_point.y + 2.0,
                                    outline="red",
                                    fill="red",
                                    width=2)
                else:
                    # If the line segment already exists in the sls, delete it
                    if lsegment[0] is not None:
                        findPreSuc.pre = None
                        findPreSuc.suc = None
                        findPreSuc(sls, lsegment[0].data)
                        sls.delete(lsegment[0].data)
                    else:
                        findPreSuc.pre = None
                        findPreSuc.suc = None
                        findPreSuc(sls, rsegment[0].data)
                        sls.delete(rsegment[0].data)

                    # Check for intersection with new successor and predecessor
                    if findPreSuc.pre is not None and findPreSuc.suc is not None and \
                            abs(findPreSuc.pre.data.index - findPreSuc.suc.data.index) > 1 and\
                            do_intersect(findPreSuc.pre.data.start, findPreSuc.pre.data.end,
                                    findPreSuc.suc.data.start,
                                    findPreSuc.suc.data.end):
                        print "Predecessor is", findPreSuc.pre.data.label, "{(", \
                            findPreSuc.pre.data.start.x, ",", findPreSuc.pre.data.start.y, "),(", \
                            findPreSuc.pre.data.end.x, ",", findPreSuc.pre.data.end.y, ")}"
                        print "Successor is", findPreSuc.suc.data.label, "{(", \
                            findPreSuc.suc.data.start.x, ",", findPreSuc.suc.data.start.y, "),(", \
                            findPreSuc.suc.data.end.x, ",", findPreSuc.suc.data.end.y, ")}"
                        print "Intersection Discovered3"
                        intersection_discovered = True
                        intersection_point = get_intersection_point(
                            findPreSuc.pre.data, findPreSuc.suc.data)
                        if automate_clicked:
                            if test is not None:
                                sls_canvas.delete(test)
                            test = sls_canvas.create_text(
                                window_width / 2,
                                20,
                                fill="darkblue",
                                font="Times 20 italic bold",
                                text="Intersection Discovered at (" +
                                str(intersection_point.x) + ", " +
                                str(intersection_point.y) + ")",
                                anchor=CENTER)
                            child_canvas.create_oval(
                                intersection_point.x - 2.0,
                                intersection_point.y - 2.0,
                                intersection_point.x + 2.0,
                                intersection_point.y + 2.0,
                                outline="red",
                                fill="red",
                                width=2)
                        return

        # If the current point has a next point, insert that line segment into the sls
        if current_point.next_point is not None:
            line_segment_2 = LineSegment(current_point,
                                         current_point.next_point,
                                         current_point.index)
            line_segment_2_dup = LineSegment(current_point.next_point,
                                             current_point,
                                             current_point.index)
            if sls is None:
                sls = Node(line_segment_2)
                index = index + 1
            else:
                lsegment = sls.lookup(line_segment_2)
                rsegment = sls.lookup(line_segment_2_dup)
                # Verify that line segment is not already present
                if lsegment[0] is None and rsegment[0] is None:
                    sls.insert(line_segment_2)
                    index = index + 1
                    findPreSuc.pre = None
                    findPreSuc.suc = None
                    findPreSuc(sls, line_segment_2)
                    # Check for intersection with predecessor
                    if findPreSuc.pre is not None and abs(
                            findPreSuc.pre.data.index -
                            line_segment_2.index) > 1:
                        if do_intersect(findPreSuc.pre.data.start,
                                        findPreSuc.pre.data.end,
                                        line_segment_2.start,
                                        line_segment_2.end):
                            print "Predecessor is", findPreSuc.pre.data.label, "{(", \
                                findPreSuc.pre.data.start.x, ",", findPreSuc.pre.data.start.y, "),(", \
                                findPreSuc.pre.data.end.x, ",", findPreSuc.pre.data.end.y, ")}"
                            print "Current Point is", line_segment_2.label, "{(", \
                                line_segment_2.start.x, ",", line_segment_2.start.y, "),(", \
                                line_segment_2.end.x, ",", line_segment_2.end.y, ")}"
                            print "Intersection Discovered4"
                            intersection_discovered = True
                            intersection_point = get_intersection_point(
                                findPreSuc.pre.data, line_segment_2)
                            if automate_clicked:
                                if test is not None:
                                    sls_canvas.delete(test)
                                test = sls_canvas.create_text(
                                    window_width / 2,
                                    20,
                                    fill="darkblue",
                                    font="Times 20 italic bold",
                                    text="Intersection Discovered at (" +
                                    str(intersection_point.x) + ", " +
                                    str(intersection_point.y) + ")",
                                    anchor=CENTER)
                                child_canvas.create_oval(
                                    intersection_point.x - 2.0,
                                    intersection_point.y - 2.0,
                                    intersection_point.x + 2.0,
                                    intersection_point.y + 2.0,
                                    outline="red",
                                    fill="red",
                                    width=2)
                            return

                    # Check for intersection with successor
                    if findPreSuc.suc is not None and abs(
                            findPreSuc.suc.data.index -
                            line_segment_2.index) > 1:
                        if do_intersect(findPreSuc.suc.data.start,
                                        findPreSuc.suc.data.end,
                                        line_segment_2.start,
                                        line_segment_2.end):
                            print "Successor is", findPreSuc.suc.data.label, "{(", \
                                findPreSuc.suc.data.start.x, ",", findPreSuc.suc.data.start.y, "),(", \
                                findPreSuc.suc.data.end.x, ",", findPreSuc.suc.data.end.y, ")}"
                            print "Current Point is", line_segment_2.label, "{(", \
                                line_segment_2.start.x, ",", line_segment_2.start.y, "),(", \
                                line_segment_2.end.x, ",", line_segment_2.end.y, ")}"
                            print "Intersection Discovered5"
                            intersection_discovered = True
                            intersection_point = get_intersection_point(
                                findPreSuc.suc.data, line_segment_2)
                            if automate_clicked:
                                if test is not None:
                                    sls_canvas.delete(test)
                                test = sls_canvas.create_text(
                                    window_width / 2,
                                    20,
                                    fill="darkblue",
                                    font="Times 20 italic bold",
                                    text="Intersection Discovered at (" +
                                    str(intersection_point.x) + ", " +
                                    str(intersection_point.y) + ")",
                                    anchor=CENTER)
                                child_canvas.create_oval(
                                    intersection_point.x - 2.0,
                                    intersection_point.y - 2.0,
                                    intersection_point.x + 2.0,
                                    intersection_point.y + 2.0,
                                    outline="red",
                                    fill="red",
                                    width=2)
                            return
                else:
                    # If the line segment already exists in the sls, delete it
                    if lsegment[0] is not None:
                        findPreSuc.pre = None
                        findPreSuc.suc = None
                        findPreSuc(sls, lsegment[0].data)
                        sls.delete(lsegment[0].data)
                    else:
                        findPreSuc.pre = None
                        findPreSuc.suc = None
                        findPreSuc(sls, rsegment[0].data)
                        sls.delete(rsegment[0].data)

                    # Check for intersection with new successor and predecessor
                    if findPreSuc.pre is not None and findPreSuc.suc is not None and \
                            abs(findPreSuc.pre.data.index - findPreSuc.suc.data.index) > 1 and \
                            do_intersect(findPreSuc.pre.data.start, findPreSuc.pre.data.end,
                                    findPreSuc.suc.data.start,
                                    findPreSuc.suc.data.end):
                        print "Predecessor is", findPreSuc.pre.data.label, "{(", \
                            findPreSuc.pre.data.start.x, ",", findPreSuc.pre.data.start.y, "),(", \
                            findPreSuc.pre.data.end.x, ",", findPreSuc.pre.data.end.y, ")}"
                        print "Successor is", findPreSuc.suc.data.label, "{(", \
                            findPreSuc.suc.data.start.x, ",", findPreSuc.suc.data.start.y, "),(", \
                            findPreSuc.suc.data.end.x, ",", findPreSuc.suc.data.end.y, ")}"
                        print "Intersection Discovered6"
                        intersection_discovered = True
                        intersection_point = get_intersection_point(
                            findPreSuc.pre.data, findPreSuc.suc.data)
                        if automate_clicked:
                            if test is not None:
                                sls_canvas.delete(test)
                            test = sls_canvas.create_text(
                                window_width / 2,
                                20,
                                fill="darkblue",
                                font="Times 20 italic bold",
                                text="Intersection Discovered at (" +
                                str(intersection_point.x) + ", " +
                                str(intersection_point.y) + ")",
                                anchor=CENTER)
                            child_canvas.create_oval(
                                intersection_point.x - 2.0,
                                intersection_point.y - 2.0,
                                intersection_point.x + 2.0,
                                intersection_point.y + 2.0,
                                outline="red",
                                fill="red",
                                width=2)
                        return

        if not automate_clicked:
            button4.wait_variable(var)
            var.set(0)
        if intersection_discovered:
            return

        label = ""
        global test
        if sls.data is not None:
            sls_text = sls.print_tree(label)
            if test is not None:
                sls_canvas.delete(test)
            test = sls_canvas.create_text(window_width / 2,
                                          20,
                                          fill="darkblue",
                                          font="Times 20 italic bold",
                                          anchor=CENTER,
                                          text=sls_text)
            print label

        last_point = current_point.y

    print "This is a simple chain"
    global button4
    if test is not None:
        sls_canvas.delete(test)
    test = sls_canvas.create_text(window_width / 2,
                                  20,
                                  fill="green",
                                  font="Times 20 italic bold",
                                  anchor=CENTER,
                                  text="This is a simple chain")

    button4.config(state="disabled")
        right_r = BSTSequences(root.right)
        for sequence in right_r:
            sequence.insert(0, root.value)
        return right_r
    """
    :type root: TreeNode
    :rtype: List[List[int]]
    """

tree = build([2, 1, 3])
print(tree)
print(BSTSequences(tree))

tree = build([1, 2])
print(tree)
print(BSTSequences(tree))

tree = None
print(BSTSequences(tree))

tree = build([5,2,None,1,4,None,None,None, None, 3])
print(tree)
print(BSTSequences(tree))


nums1 = [1, 2]
nums2 = [3, 4]
root = Node(0)
print(buildTree(root, nums1, nums2))
print(root)
                root = None
                return temp

            elif root.right is None:
                temp = root.left
                root = None
                return temp

            else:
                temp = self.getMinVal(root.right)
                root.val = temp.val
                root.right = self.delete(root.right, temp.val)
                return root

        return root

    def getMinVal(self, root):
        minval = root
        while minval.left is not None:
            minval = minval.left
        return minval


if __name__ == "__main__":
    bst = BinarySearchTree(Node(50))
    bst.insert(bst, Node(40))
    bst.insert(bst, Node(60))
    bst.insert(bst, Node(70))
    bst.insert(bst, Node(80))
    bst.inorder(bst)
Example #21
0
 def create_tree(self, nums, root, i):
     if i < len(nums):
         root = TN(nums[i])
         root.left = self.create_tree(nums, root.left, 2 * i + 1)
         root.right = self.create_tree(nums, root.right, 2 * i + 2)
     return root
Example #22
0
 def __init__(self, val):
     Node.__init__(self, val)
     self.height = 1
Example #23
0
    def test_insert_same_key(self):
        node = Node(3, 'value')

        assert node.insert(3, 'value') is False
Example #24
0
            print("\n---Add Node")
            root.pprint(index=True)
            idx = int(input("Enter index of node:"))

            try:
                root[idx]
                if root[idx].left == None and root[idx].right == None:
                    #left right
                    print("1-add left node,\n2-add right node\n0-cancel")
                    opt_add = int(input("Select option: "))

                    if opt_add == 1:
                        #left
                        print("\n---Add Left Node")
                        val = int(input("Enter value: "))
                        root[idx].left = Node(val)
                        print(root)
                    elif opt_add == 2:
                        #right
                        print("\n---Add Right Node")
                        val = int(input("Enter value: "))
                        root[idx].right = Node(val)
                        print(root)
                    elif opt_add == 0:
                        print("\n---Canceled")
                        #cancel
                        continue
                    else:
                        print("Wrong option\n")
                        continue
Example #25
0
    def test_init(self):
        node = Node(3, 'value')

        assert node.key == 3
        assert node.value == 'value'
Example #26
0
def perfectTree(i, vals):
    if i < len(vals):
        return Node(vals[i],
                    left=perfectTree((i + 1) * 2 - 1, vals),
                    right=perfectTree((i + 1) * 2, vals))

class SameTree:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if p is None and q is None:
            return True

        if (p is not None and q is not None) and (p.val == q.val):
            return self.isSameTree(p.left, q.left) and self.isSameTree(
                p.right, q.right)

        return False


obj = SameTree()
root1 = Node(1)
root1.left = Node(2)
root1.right = Node(3)

root2 = Node(1)
root2.left = Node(2)
root2.right = Node(3)

print(obj.isSameTree(root1, root2))

root3 = Node(1)
root3.left = Node(2)

root4 = Node(1)
root4.right = Node(2)
Example #28
0

def inorderTraversal(tree, inorderArray):
    if tree is not None:
        inorderTraversal(tree.left, inorderArray)
        inorderArray.append(tree.value)
        inorderTraversal(tree.right, inorderArray)
    return inorderArray


def findKthLargestValueInBst(tree, k):
    array = inorderTraversal(tree, [])
    return array[len(array) - k]


root = Node(15)
root.left = Node(5)
root.right = Node(20)
root.left.left = Node(2)
root.left.right = Node(5)
root.right.left = Node(17)
root.right.right = Node(22)
root.left.left.left = Node(1)
root.left.left.right = Node(3)

print(findKthLargestValueInBst(root, 3))

"""
Java Solution
-------------
import java.util.*;
Example #29
0

"""解法2:辅助栈
- 时间复杂度:O(N)
- 空间复杂度:O(N)
"""
# class Solution:
#     def mirrorTree(self, root: TreeNode) -> TreeNode:
#         if not root:
#             return
#         stack = [root]
#         while stack:
#             node = stack.pop()
#             if node.left:
#                 stack.append(node.left)
#             if node.right:
#                 stack.append(node.right)
#             node.left, node.right = node.right, node.left
#         return root

if __name__ == "__main__":
    root = TreeNode(4)
    root.left = TreeNode(2)
    root.right = TreeNode(7)
    root.left.left = TreeNode(1)
    root.left.right = TreeNode(3)
    root.right.left = TreeNode(6)
    root.right.right = TreeNode(9)
    print(root)
    print(Solution().mirrorTree(root))
Example #30
0
    def test_insert_same_key(self):
        node = Node(3, 'value')

        assert node.insert(3, 'value') is False
Example #31
0
def createNodes(alphabet):
	nodes = {}
	for ele in alphabet.keys():
		nodes[ele] = Node(ele)
	return nodes
Example #32
0
from binarytree import tree, bst, Node


class MyNode:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right


a = tree(height=4, is_perfect=False)
print(a)
b = bst(height=3, is_perfect=True)
print(b)

root = Node(20)
root.left = Node(10)
root.right = Node(30)
root.right.right = Node(50)
root.left.left = Node(2)
print(root)

print('*' * 50)
c = tree(height=5, is_perfect=False)
print(c)
num = int(input('Какое число найти: '))


def search(bin_tree, number, path=''):
    if bin_tree.value == number:
        return f'Число {number} найдено по следующему пути:\nКорень{path}'
def buildBtreeWithNodeLib():
    hHeap = Node('*')
    hHeap.left = Node('*')
    hHeap.left.right = Node('a')
    hHeap.left.left = Node('*')
    hHeap.left.left.left = Node('c')
    hHeap
    hHeap.right = Node('*')
    hHeap.right.left = Node('t')
    hHeap.right.right = Node('*')
    hHeap.right.right.right = Node('s')
    print(hHeap)
Example #34
0
    if root_node.right and root_node.right.value < value:
        return False

    return check_tree(root_node.left, min_v=min_v, max_v=value) \
           and check_tree(root_node.right, min_v=value, max_v=max_v)


# create random binary tree
non_sorted_tree = tree(height=3, is_perfect=False)
print(non_sorted_tree)

result = check_tree(non_sorted_tree)
print('Non sorted tree:', result)

# Build the new tree from the example in the video:
sorted_tree = Node(50)
sorted_tree.left = Node(10)
sorted_tree.right = Node(80)
sorted_tree.left.left = Node(5)
sorted_tree.left.right = Node(30)
sorted_tree.left.right.left = Node(20)
sorted_tree.left.right.left = Node(40)
sorted_tree.right.left = Node(70)
sorted_tree.right.right = Node(90)
sorted_tree.right.right.left = Node(85)

print(sorted_tree)

# Check it
result = check_tree(sorted_tree)
print('Example tree:', result)
        self.pushAll(root)

    # @return a boolean, whether we have a next smallest number
    def hasNext(self):
        if self.stack:
            return True
        return False

    # @return an integer, the next smallest number
    def next(self):
        tmpNode = self.stack.pop()
        self.pushAll(tmpNode.right)
        return tmpNode.value

    def pushAll(self, node):
        while node is not None:
            self.stack.append(node)
            node = node.left

root = Treenode(2)
root.left = Treenode(1)
root.left.left = Treenode(0)
root.right = Treenode(3)
print(root)

S = Solution(root)

print S.next()
print S.next()
print S.hasNext()
            return s == 0
        else:
            ans = 0

            # Otherwise check both subtrees
            subSum = s - root.value

            # If we reach a leaf node and sum becomes 0, then
            # return True
            if (subSum == 0 and root.left == None and root.right == None):
                return True

            if root.left is not None:
                ans = ans or self.roottoleafpathSum(root.left, subSum)
            if root.right is not None:
                ans = ans or self.roottoleafpathSum(root.right, subSum)

            return ans


S = Solution()
s = 21
root = TN(10)
root.left = TN(8)
root.right = TN(2)
root.left.right = TN(5)
root.left.left = TN(3)
root.right.left = TN(2)
print(root)

print S.roottoleafpathSum(root, s)
from binarytree import Node as TN

class Solution(object):
    def invertbinaryTree(self, root):
        if root is not None:
            root.left, root.right = \
                self.invertbinaryTree(root.right), self.invertbinaryTree(root.left)
        return root

S = Solution()

root = TN(4)
root.left = TN(2)
root.left = TN(2)
root.right = TN(7)
root.left.left = TN(1)
root.left.right = TN(3)
root.right.left = TN(6)
root.right.right = TN(9)

print root

print S.invertbinaryTree(root)
Example #38
0
#use bfs indices to manipulate nodes
from binarytree import Node

root = Node(1)
root.left = Node(4)
root.right = Node(7)
root.left.right = Node(8)
root.right.left = Node(9)
root.right.right = Node(6)
print "tree: "
print(root)

print "with indices "
root.pprint(index=True, delimiter=',')

idx = 2
print "node/subtree at index ", idx, root[idx]
print "changing node val at ", idx
root[idx] = Node(20)
root.pprint(index=True, delimiter=',')

idx = 4
print "changing subtree at ", idx
root[idx] = Node(40, left=Node(12), right=Node(80))
root.pprint(index=True, delimiter=',')

idx = 1
print "delete at ", idx
del root[1]
root.pprint(index=True, delimiter=',')
    def k_path_sum(self, root, k):
        if root is None:
            return
        #print 'Visiting {}'.format(root.value)
        self.path.append(root.value)
        self.k_path_sum(root.left, k)
        self.k_path_sum(root.right, k)
        #print 'Current path: {}'.format(self.path)
        currsum = 0
        for i in reversed(xrange(len(self.path))):
            currsum += self.path[i]
            if currsum == k:
                print self.path[i:]
        self.path.pop()

root = Treenode(1)
root.left = Treenode(3)
root.left.left = Treenode(2)
root.left.right = Treenode(1)
root.left.right.left = Treenode(1)
root.right = Treenode(-1)
root.right.left = Treenode(4)
root.right.left.left = Treenode(1)
root.right.left.right = Treenode(2)
root.right.right = Treenode(5)
root.right.right.right = Treenode(2)
print(root)

S = Solution()
S.k_path_sum(root, 5)
        if tree_1 is not None and tree_2 is not None:
            return ((tree_1.value == tree_2.value) and
                    self.identical_trees(tree_1.left, tree_2.left) and
                    self.identical_trees(tree_1.right, tree_2.right))

        return False

    def isSubtree(self, s, t):
        if not s:
            return False
        if self.identical_trees(s, t):
            return True
        if self.isSubtree(s.left, t) or self.isSubtree(s.right, t):
            return True
        return False

S = Solution()
root1 = Treenode(30)
root1.left = Treenode(20)
root1.right = Treenode(40)
root1.left.left = Treenode(20)
root1.left.right = Treenode(40)
print root1

root2 = Treenode(20)
root2.left = Treenode(20)
root2.right = Treenode(40)
print root2

print S.isSubtree(root1, root2)
Example #41
0
class Tree:
    heap = []
    codes = {}
    reverseMap = {}
    root = Node(0, 0)
Example #42
0
                    return node, 1

            if node.right is not None:
                right_node, found_one = delete_node(node.right, node_val)
                if found_one is not None:
                    node.right = right_node
                    return node, 1
            return None, None

        delete_node(self.root, node_val)


tree = BinaryTree(3)
print(tree.root)
random_node = tree.find_random_node()
found_node = tree.find(random_node.value)

assert random_node.value == found_node.value
tree.insert(Node(55))
tree.insert(Node(105))
tree.insert(Node(125))
print(tree.root)

tree_values = tree.root.values
tree_values = list(filter(None, tree_values))
idx = int(np.random.randint(0, len(tree_values)))
val = tree_values[idx]
print("remove", val)
tree.delete(val)
print(tree.root)
#import sys
from binarytree import tree
from binarytree import Node
import time
start = time.time()

n = int(input().strip())
ls = list(map(int, input().strip().split()))
store = [[-3 for i in range(3)] for j in range(n)]
#sys.setrecursionlimit(3*n)
root = Node(0.0)
root2 = Node(0)
result = []
#lll=input().strip().split()
#ls=[int(i) for i in lll]


def qq(ind, rest, result):
    print('returning ', result, ' for', ' rec(', ind, rest, ')', '')


def pq(ind, rest):
    a = ind + 1
    b = rest + 1
    print('calls rec(', a, ',0) and calls rec(', a, ',', b, ')')


def p(ind, rest):
    print('ind,rest: ', ind, rest, store)

Example #44
0
class TestNode:
    def test_init(self):
        node = Node(3, 'value')

        assert node.key == 3
        assert node.value == 'value'

    def test_insert_same_key(self):
        node = Node(3, 'value')

        assert node.insert(3, 'value') is False

    def test_insert_no_left_child(self):
        node = Node(3, 'value')

        assert node.left_child is None
        assert node.insert(2, 'left_value') is True
        assert node.left_child is not None
        assert node.left_child.key == 2
        assert node.left_child.value == 'left_value'

    def test_insert_left_child(self):
        node = Node(3, 'value')
        node.insert(2, 'left_value')

        assert node.left_child.left_child is None
        node.insert(1, 'left_child_value')
        assert node.left_child.left_child is not None
        assert node.left_child.left_child.key == 1
        assert node.left_child.left_child.value == 'left_child_value'

    def test_insert_no_right_child(self):
        node = Node(3, 'value')

        assert node.right_child is None
        assert node.insert(4, 'right_value') is True
        assert node.right_child is not None
        assert node.right_child.key == 4
        assert node.right_child.value == 'right_value'

    def test_insert_right_child(self):
        node = Node(3, 'value')
        node.insert(4, 'right_value')

        assert node.right_child.right_child is None
        node.insert(5, 'right_child_value')
        assert node.right_child.right_child is not None
        assert node.right_child.right_child.key == 5
        assert node.right_child.right_child.value == 'right_child_value'

    @pytest.mark.parametrize('node, left_child, right_child, search_key', [
        (Node(4, 'a'), 2, 5, 4),
        (Node(4, 'a'), 2, 5, 2),
        (Node(4, 'a'), 2, 5, 5),
    ])
    def test_find_key(self, node, left_child, right_child, search_key):
        node.insert(left_child, 'b')
        node.insert(right_child, 'c')

        assert node.find(search_key).key == search_key

    @pytest.mark.parametrize('node, left_child, right_child, search_key', [
        (Node(4, 'a'), 2, 5, 6),
        (Node(4, 'a'), 2, 5, 3),
        (Node(4, 'a'), None, None, 6),
        (Node(4, 'a'), None, None, 3),
    ])
    def test_key_not_in_node(self, node, left_child, right_child, search_key):
        if left_child:
            node.insert(left_child, 'b')

        if right_child:
            node.insert(right_child, 'c')

        assert node.find(search_key) is None

    def test_get_node_list(self):
        node = Node(4, 'a')
        node.insert(2, 'b')
        node.insert(5, 'c')
        node.insert(1, 'd')
        node.insert(3, 'e')
        node.insert(6, 'f')

        assert node.get_node_list(node) == [1, 2, 3, 4, 5, 6]
from binarytree import Node


def invertBinaryTree(tree):
    if not tree:
        return None
    right,left = invertBinaryTree(tree.right),invertBinaryTree(tree.left)
    tree.left,tree.right = right,left
    return tree


root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.left.left.left = Node(8)
root.left.left.right = Node(9)

print(invertBinaryTree(root))
from random import seed
from collections import deque
"""
deque: double-ended queue
"""

# Build a tree with binarytree.tree
seed(3)
my_tree = tree(height = 3, is_perfect = False)
#print("Generate with built-in tree method")
#print(type(my_tree)) # <class 'binarytree.Node'>
#print(my_tree)


# Build with Node
root = Node(1)
root.left = Node(2)
root.right = Node(3)
#print("Generate with built-in Node method")
#print(root)
#print(root.value)

# Build tree using a list
data1 = [10,5,-3,3,2,None,11,3,-2,None,1]
data2 = [3,5,2,1,4,6,7,8,9,10,11,12,13,14]

def create_btree_with_list(data):

	tree = Node(data.pop(0))
	fringe = deque([tree])