def preOrderTraverse(tree, array): array.append(tree.value) if tree.left is not None: preOrderTraverse(tree.left, array) if tree.right is not None: preOrderTraverse(tree.right, array) return array def postOrderTraverse(tree, array): if tree.left is not None: postOrderTraverse(tree.left, array) if tree.right is not None: postOrderTraverse(tree.right, array) array.append(tree.value) return array root = Node(10) root.left = Node(5) root.right = Node(15) root.left.left = Node(2) root.left.right = Node(5) root.right.right = Node(22) root.left.left.left = Node(1) print("Inorder Traversal ", inOrderTraverse(root, [])) print("Preorder Traversal ", preOrderTraverse(root, [])) print("Postorder Traversal ", postOrderTraverse(root, []))
:rtype: int """ if not root: return 0 lstTree = [] self.addNoteToList(root, lstTree) lstTree.sort() minValue = sys.maxint for i in xrange(len(lstTree) - 1): minValue = min(minValue, abs(lstTree[i + 1] - lstTree[i])) return minValue def addNoteToList(self, root, lstTree): if not root: return lstTree.append(root.value) if root.left: self.addNoteToList(root.left, lstTree) if root.right: self.addNoteToList(root.right, lstTree) root = Node(236) root.left = Node(104) root.right = Node(701) root.left.right = Node(227) root.right.right = Node(911) print root print Solution().getMinimumDifference(root)
return prev 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()
#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 test_node_set_attributes(): root = Node(1) assert root.left is None assert root.right is None assert root.val == 1 assert root.value == 1 assert repr(root) == "Node(1)" root.value = 2 assert root.value == 2 assert root.val == 2 assert repr(root) == "Node(2)" root.val = 1 assert root.value == 1 assert root.val == 1 assert repr(root) == "Node(1)" left_child = Node(2) root.left = left_child assert root.left is left_child assert root.right is None assert root.val == 1 assert root.left.left is None assert root.left.right is None assert root.left.val == 2 assert repr(left_child) == "Node(2)" right_child = Node(3) root.right = right_child assert root.left is left_child assert root.right is right_child assert root.val == 1 assert root.right.left is None assert root.right.right is None assert root.right.val == 3 assert repr(right_child) == "Node(3)" last_node = Node(4) left_child.right = last_node assert root.left.right is last_node assert repr(root.left.right) == "Node(4)" with pytest.raises(NodeValueError) as err: # noinspection PyTypeChecker Node("this_is_not_an_integer") assert str(err.value) == "node value must be a float or int" with pytest.raises(NodeTypeError) as err: # noinspection PyTypeChecker Node(1, "this_is_not_a_node") assert str(err.value) == "left child must be a Node instance" with pytest.raises(NodeTypeError) as err: # noinspection PyTypeChecker Node(1, Node(1), "this_is_not_a_node") assert str(err.value) == "right child must be a Node instance" with pytest.raises(NodeValueError) as err: root.val = "this_is_not_an_integer" assert root.val == 1 assert str(err.value) == "node value must be a float or int" with pytest.raises(NodeValueError) as err: root.value = "this_is_not_an_integer" assert root.value == 1 assert str(err.value) == "node value must be a float or int" with pytest.raises(NodeTypeError) as err: root.left = "this_is_not_a_node" assert root.left is left_child assert str(err.value) == "left child must be a Node instance" with pytest.raises(NodeTypeError) as err: root.right = "this_is_not_a_node" assert root.right is right_child assert str(err.value) == "right child must be a Node instance"
from binarytree import Node def inorder(root): if root.left is None and root.right is None: return root.value if root.left is not None: output = inorder(root.left) + root.value + inorder(root.right) if root.value in ['+', '-']: return "({})".format(output) else: return output if __name__ == "__main__": root = Node('+') root.left = Node('x') root.right = Node('x') root.left.left = Node('3') root.left.right = Node('+') root.left.right.left = Node('1') root.left.right.right = Node('2') root.right.left = Node('+') root.right.left.right = Node('4') root.right.left.left = Node('7') root.right.right = Node('2') print(root) print(inorder(root))
def test_search_bts_1(): numbers = [50, 30, 20, 40, 70, 60, 80] T = Tree(numbers) node = Node(50, Node(30), Node(70)) assert T.search(50) == T.get_root() assert compare_nodes(T.search(50), node) is True
def abrSupprimerMax(A): if A.right == None: return A.left, A.val else: B, maximum = abrSupprimerMax(A.right) return Node(A.val, A.left, B), maximum
if not L and not R: continue if L and R: if L.data != R.data: return False dq.append(L.left) dq.append(R.right) dq.append(L.right) dq.append(R.left) else: return False return True if __name__ == '__main__': left = Node(6) left.right = Node(2) left.right.right = Node(3) right = Node(6) right.left = Node(2) right.left.left = Node(3) root = Node(314, left, right) print(symmetric(root)) nodes = [1, 2, 2, 4, 3, 3, 4] tree = BinaryTree() for node in nodes: tree.add(node) print(sym_iterative(tree.root))
else: break return root def magnitude(a): if a.left is None: return a.value else: return 3 * magnitude(a.left) + 2 * magnitude(a.right) best = None for n1 in range(len(numbers)): for n2 in range(len(numbers)): print(n1, n2) if n1 == n2: continue s = Node(-1) s.left = maketree(numbers[n1]) s.right = maketree(numbers[n2]) reduce(s) print(s) mag = magnitude(s) if best is None or mag > best: best = mag print(best, mag, makelist(s))
# Что такое дерево # Классификация дерева # Создание деревьев в Python # Самый простой способ создать дерево - создать свой собственный класс from binarytree import tree, bst, Node, build class MyNode: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right a = tree(height=4, is_perfect=False) print(a) b = bst(height=4, is_perfect=True) print(b) c = Node(7) c.left = Node(3) c.right = Node(1) c.left = Node(5) c.right.left = Node(9) c.right.right = Node(13) print(c)
def test_heap_float_values(): root = Node(1.0) root.left = Node(0.5) root.right = Node(1.5) assert root.height == 1 assert root.is_balanced is True assert root.is_bst is True assert root.is_complete is True assert root.is_max_heap is False assert root.is_min_heap is False assert root.is_perfect is True assert root.is_strict is True assert root.leaf_count == 2 assert root.max_leaf_depth == 1 assert root.max_node_value == 1.5 assert root.min_leaf_depth == 1 assert root.min_node_value == 0.5 assert root.size == 3 for printer in [builtin_print, pprint_default]: lines = printer([1.0]) assert lines == ["1.0"] lines = printer([1.0, 2.0]) assert lines == [" _1.0", " /", "2.0"] lines = printer([1.0, None, 3.0]) assert lines == ["1.0_", " \\", " 3.0"] lines = printer([1.0, 2.0, 3.0]) assert lines == [" _1.0_", " / \\", "2.0 3.0"] lines = printer([1.0, 2.0, 3.0, None, 5.0]) assert lines == [ " _____1.0_", " / \\", "2.0_ 3.0", " \\", " 5.0", ] for builder in [tree, bst, heap]: for _ in range(REPETITIONS): root = builder() root_copy = copy.deepcopy(root) for node in root: node.value += 0.1 assert root.height == root_copy.height assert root.is_balanced == root_copy.is_balanced assert root.is_bst == root_copy.is_bst assert root.is_complete == root_copy.is_complete assert root.is_max_heap == root_copy.is_max_heap assert root.is_min_heap == root_copy.is_min_heap assert root.is_perfect == root_copy.is_perfect assert root.is_strict == root_copy.is_strict assert root.is_symmetric == root_copy.is_symmetric assert root.leaf_count == root_copy.leaf_count assert root.max_leaf_depth == root_copy.max_leaf_depth assert root.max_node_value == root_copy.max_node_value + 0.1 assert root.min_leaf_depth == root_copy.min_leaf_depth assert root.min_node_value == root_copy.min_node_value + 0.1 assert root.size == root_copy.size
def test_tree_properties(): root = Node(1) assert root.properties == { "height": 0, "is_balanced": True, "is_bst": True, "is_complete": True, "is_max_heap": True, "is_min_heap": True, "is_perfect": True, "is_strict": True, "is_symmetric": True, "leaf_count": 1, "max_leaf_depth": 0, "max_node_value": 1, "min_leaf_depth": 0, "min_node_value": 1, "size": 1, } assert root.height == 0 assert root.is_balanced is True assert root.is_bst is True assert root.is_complete is True assert root.is_max_heap is True assert root.is_min_heap is True assert root.is_perfect is True assert root.is_strict is True assert root.is_symmetric is True assert root.leaf_count == 1 assert root.max_leaf_depth == 0 assert root.max_node_value == 1 assert root.min_leaf_depth == 0 assert root.min_node_value == 1 assert root.size == len(root) == 1 root.left = Node(2) assert root.properties == { "height": 1, "is_balanced": True, "is_bst": False, "is_complete": True, "is_max_heap": False, "is_min_heap": True, "is_perfect": False, "is_strict": False, "is_symmetric": False, "leaf_count": 1, "max_leaf_depth": 1, "max_node_value": 2, "min_leaf_depth": 1, "min_node_value": 1, "size": 2, } assert root.height == 1 assert root.is_balanced is True assert root.is_bst is False assert root.is_complete is True assert root.is_max_heap is False assert root.is_min_heap is True assert root.is_perfect is False assert root.is_strict is False assert root.is_symmetric is False assert root.leaf_count == 1 assert root.max_leaf_depth == 1 assert root.max_node_value == 2 assert root.min_leaf_depth == 1 assert root.min_node_value == 1 assert root.size == len(root) == 2 root.right = Node(3) assert root.properties == { "height": 1, "is_balanced": True, "is_bst": False, "is_complete": True, "is_max_heap": False, "is_min_heap": True, "is_perfect": True, "is_strict": True, "is_symmetric": False, "leaf_count": 2, "max_leaf_depth": 1, "max_node_value": 3, "min_leaf_depth": 1, "min_node_value": 1, "size": 3, } assert root.height == 1 assert root.is_balanced is True assert root.is_bst is False assert root.is_complete is True assert root.is_max_heap is False assert root.is_min_heap is True assert root.is_perfect is True assert root.is_strict is True assert root.is_symmetric is False assert root.leaf_count == 2 assert root.max_leaf_depth == 1 assert root.max_node_value == 3 assert root.min_leaf_depth == 1 assert root.min_node_value == 1 assert root.size == len(root) == 3 root.left.left = Node(4) assert root.properties == { "height": 2, "is_balanced": True, "is_bst": False, "is_complete": True, "is_max_heap": False, "is_min_heap": True, "is_perfect": False, "is_strict": False, "is_symmetric": False, "leaf_count": 2, "max_leaf_depth": 2, "max_node_value": 4, "min_leaf_depth": 1, "min_node_value": 1, "size": 4, } assert root.height == 2 assert root.is_balanced is True assert root.is_bst is False assert root.is_complete is True assert root.is_max_heap is False assert root.is_min_heap is True assert root.is_perfect is False assert root.is_strict is False assert root.is_symmetric is False assert root.leaf_count == 2 assert root.max_leaf_depth == 2 assert root.max_node_value == 4 assert root.min_leaf_depth == 1 assert root.min_node_value == 1 assert root.size == len(root) == 4 root.right.left = Node(5) assert root.properties == { "height": 2, "is_balanced": True, "is_bst": False, "is_complete": False, "is_max_heap": False, "is_min_heap": False, "is_perfect": False, "is_strict": False, "is_symmetric": False, "leaf_count": 2, "max_leaf_depth": 2, "max_node_value": 5, "min_leaf_depth": 2, "min_node_value": 1, "size": 5, } assert root.height == 2 assert root.is_balanced is True assert root.is_bst is False assert root.is_complete is False assert root.is_max_heap is False assert root.is_min_heap is False assert root.is_perfect is False assert root.is_strict is False assert root.is_symmetric is False assert root.leaf_count == 2 assert root.max_leaf_depth == 2 assert root.max_node_value == 5 assert root.min_leaf_depth == 2 assert root.min_node_value == 1 assert root.size == len(root) == 5 root.right.left.left = Node(6) assert root.properties == { "height": 3, "is_balanced": False, "is_bst": False, "is_complete": False, "is_max_heap": False, "is_min_heap": False, "is_perfect": False, "is_strict": False, "is_symmetric": False, "leaf_count": 2, "max_leaf_depth": 3, "max_node_value": 6, "min_leaf_depth": 2, "min_node_value": 1, "size": 6, } assert root.height == 3 assert root.is_balanced is False assert root.is_bst is False assert root.is_complete is False assert root.is_max_heap is False assert root.is_min_heap is False assert root.is_perfect is False assert root.is_strict is False assert root.is_symmetric is False assert root.leaf_count == 2 assert root.max_leaf_depth == 3 assert root.max_node_value == 6 assert root.min_leaf_depth == 2 assert root.min_node_value == 1 assert root.size == len(root) == 6 root.left.left.left = Node(7) assert root.properties == { "height": 3, "is_balanced": False, "is_bst": False, "is_complete": False, "is_max_heap": False, "is_min_heap": False, "is_perfect": False, "is_strict": False, "is_symmetric": False, "leaf_count": 2, "max_leaf_depth": 3, "max_node_value": 7, "min_leaf_depth": 3, "min_node_value": 1, "size": 7, } assert root.height == 3 assert root.is_balanced is False assert root.is_bst is False assert root.is_complete is False assert root.is_max_heap is False assert root.is_min_heap is False assert root.is_perfect is False assert root.is_strict is False assert root.is_symmetric is False assert root.leaf_count == 2 assert root.max_leaf_depth == 3 assert root.max_node_value == 7 assert root.min_leaf_depth == 3 assert root.min_node_value == 1 assert root.size == len(root) == 7
def test_tree_validate(): class TestNode(Node): def __setattr__(self, attr, value): object.__setattr__(self, attr, value) root = Node(1) root.validate() # Should pass root = Node(1) root.left = Node(2) root.validate() # Should pass root = Node(1) root.left = Node(2) root.right = Node(3) root.validate() # Should pass root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.left.right.left = Node(6) root.validate() # Should pass root = TestNode(1) root.left = "not_a_node" with pytest.raises(NodeTypeError) as err: root.validate() assert str(err.value) == "invalid node instance at index 1" root = TestNode(1) root.right = TestNode(2) root.right.val = "not_an_integer" with pytest.raises(NodeValueError) as err: root.validate() assert str(err.value) == "invalid node value at index 2" root = TestNode(1) root.left = TestNode(2) root.left.right = root with pytest.raises(NodeReferenceError) as err: root.validate() assert str(err.value) == "cyclic reference at Node(1) (level-order index 4)"
def main(): root = Node(0) depth = 3 generate_btree4encode(root, depth) print(root)
def add(self, val): if self.root is None: self.rootT = Node(val) self.root = NodeC(val) else: self._add(val, self.root, self.rootT)
# 判断二叉树是否是对称的 from binarytree import Node def isSymmetric(t): return isSymmetricInner(t, t) def isSymmetricInner(t1, t2): if t1 == None and t2 == None: return True if t1 == None or t2 == None: return False if t1.value != t2.value: return False left = isSymmetricInner(t1.left, t2.right) # 注意这里,对称和镜像不同之处 right = isSymmetricInner(t1.right, t2.left) return left and right t = Node(1) t.left = t.right = Node(8) t.left.left = t.right.right = Node(9) print(t) print(isSymmetric(t))
# можно воспользоваться библиотекой binary tree # с помощью функции tree: print('создано с помощью функции "tree"', '*' * 33, sep='\n') a = tree(height=4, is_perfect=False) # height=4 задаем высоту дерева, is_perfect=False указываем - что оно не # расширенное print(a) # с помощью функции bst строятся бинарные поисковые деревья: print('создано с помощью функции "bst"', '*' * 33, sep='\n') b = bst(height=4, is_perfect=True) print(b) # с помощью создания экземпляров класса Node: print('создано с помощью класса "Node"', '*' * 33, sep='\n') c = Node(15) # задаем корень дерева c.left = Node(7) c.right = Node(23) c.left.left = Node(3) c.left.right = Node(11) c.right.left = Node(19) c.right.right = Node(27) c.left.left.left = Node(1) c.left.left.right = Node(5) c.left.right.left = Node(9) c.left.right.right = Node(13) c.right.left.left = Node(17) c.right.left.right = Node(21) c.right.right.left = Node(25) c.right.right.right = Node(29) print(c)
def test_search_avl_2(): numbers = [10, 20, 30, 40, 50, 25] T = AvlTree(numbers) node = Node(20, Node(10), Node(25)) assert compare_nodes(T.search(20), node)
sums_array.append(currentSum) return if root.left is not None: currentSum += root.left.value branchSumsHelper(root.left, currentSum, sums_array) currentSum -= root.left.value if root.right is not None: currentSum += root.right.value branchSumsHelper(root.right, currentSum, sums_array) currentSum -= root.right.value def branchSums(root): sums_array = [] branchSumsHelper(root, root.value, sums_array) return sums_array 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) root.left.right.left = Node(10) print(branchSums(root))
def test_search_bts_3(): numbers = [50, 30, 20, 40, 70, 60, 80] T = Tree(numbers) node = Node(30, Node(20), Node(40)) assert compare_nodes(T.search(30), node)
async def bst(self, ctx): """ `!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, num): 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, num): 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): 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): graph = root.graphviz() graph.render("bst", format="png") while True: if display: draw_bst(root) text = f"```{root}\n```" await ctx.send(text, file=discord.File("bst.png")) display = False def check(m): return m.channel.id == ctx.channel.id and m.author.id == ctx.author.id try: message = await self.bot.wait_for("message", timeout=timeout, check=check) 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=max( filter(lambda x: x is not None, root.left.values))) if root.right: embed.add_field(name="In-Order Successor:", value=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 Exception: 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
""" 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))
def encode_string(bst, li): bst = Node(36) for i in range(len(li)): if li[i] > bst.value: bst.right = Node(int(li[i])) return encode_string(bst.right, li)