If insertion/deletion from a binary tree is efficient, while maintaining ability to get item by index

I can’t quite figure this out. Say you have a binary tree where the left or right nodes correspond to 0 or 1 and a group of levels form a chain which is the index of the node. So you have 10010 which is 18 in decimal, so index 18 (say we count from 1 instead of 0).

      1     0   1    0 1 0 1         0 1         ... 

We build up some binary tree/trie. I’m trying to figure out if you can delete and add nodes to the trie without having to rewrite the whole subbranch to the right of where you insert or delete, or if there is a simple few-step operation to somehow sort of rotate the tree branch on insert/delete such that you don’t have to rewrite a big chunk of the tree. The reason is, you want to maintain the position of the nodes, so if you have nodes at position 6, 7, and 8, if you remove node 4, then they become positions 5, 6, 7. Do you get this for free somehow, or do you have to rewrite all of there positions in the tree? I can’t quite see how it would look, wondering if one could explain how it would work.

find derived tree for CFG

i need to draw the derived tree for 1-2-3(3-4)*5*6 from the grammar ,how many possibility derived tree are there ?

Vn={expr,term,factor,number}
Vt={(,),-,,0…9}
P={ expr->expr-expr|term
term->term
factor|factor
factor->number|(expr)
number->0|1|2|3|4|5|6|7|8|9
}
S=expr

possbility that i can find are: (1-2)-(((3-4)*5)*6), 1-(2-( ((3-4)*5) *6))

are there other possibility?

Maximum Width binary tree

Here is my code for the LeetCode problem

For a given binary tree, find the maximum width of the binary tree. The width of one level is defined as the length between the end-nodes even if there are None nodes in between

My code (in PyCharm) passess all the given tests but does not seem to pass on the LeetCode website. I am not sure why this is, so please don’t try plugging it into the website as I assume the way I have built a binary tree is different to their method.

class Node:      def __init__(self, data):         self.data = data         self.left = None         self.right = None      level_width = {0: [0, 0]}      def get_width(self, root, level=0, pointer=1):         if root.left:             if level + 1 not in self.level_width:                 self.level_width[level + 1] = [pointer * 2, 0]             self.level_width[level + 1][0] = min(self.level_width[level + 1][0], pointer * 2)             self.get_width(root.left, level + 1, pointer * 2)         if root.right:             if level + 1 not in self.level_width:                 self.level_width[level + 1] = [9999, pointer * 2 + 1]             self.level_width[level + 1][1] = max(self.level_width[level + 1][1], level + 1, pointer * 2 + 1)             self.get_width(root.right, level + 1, pointer * 2 + 1)         return      def widthOfBinaryTree(self, root):         """           :type root: TreeNode           :rtype: int           """         self.get_width(root)         max_distance = 1         for k, v in self.level_width.items():             max_distance = max(max_distance, v[1] - v[0] + 1)         return max_distance   root = Node(1) root.left = Node(3) root.left.left = Node(5) root.left.left.left = Node(6) root.right = Node(2) root.right.right = Node(9) root.right.right.right = Node(7)  print(root.widthOfBinaryTree(root)) 

Nodes in a binary search tree that span a range

I have a binary search tree of height $ h$ with an integer in each leaf. I also have a range $ [\ell,u]$ . I want to find a set of nodes that span the range $ [\ell,u]$ , i.e., a set $ S$ of nodes such that the leaves under $ S$ form all (and only) those leaves containing integers in the range $ [\ell,u]$ . How large does $ S$ need to be, in the worst case, as a function of the height $ h$ ? How do I find such a set explicitly?

Vue element UI tree Personalizado

Requiero personalizar el componente de Element Ui pero no se como aƱadirle los compoenentes que dependen del mismo algo asi como esto:

  <el-tree     :data="data"     show-checkbox     node-key="id"     :props="producProp"   >       <el-checkbox v-model="node.checked"></el-checkbox>   </el-tree> 

me gustaria personalizar tanto el checkbox como el label, tienen alguna idea?

git Create Tree from Arbitrary Directory (works in bare repository)

I made a script for a project I’m working on to create a tree object from a filesystem directory, without any working tree operations (can be run in a bare repository). The tree can be inserted into (a) commit(s) by using an index filter that invokes git read-tree --prefix=</...>.

#!/bin/bash # createSubtreeRec <path> # Creates a subtree with all the contents of path # does not need to be in a work tree. # Tree and related objects are added to the repository (unreachable) # recursive. # Prints the line that should be used to include the built tree in a parent #   in the form used by git mktree on stdout. This might be a blob or tree. #   <mode> <type> <hash>    <name> #         ^space ^space    ^tab function createSubtreeRec () {     local path="$  1"     local hash=""     local type=""     local mode=""     local treeData=""     #echo "" >&2     if [ -d "$  path" ]; then         for fullpath in $  path/*; do             f=$  (basename $  fullpath)             if [ -f "$  path/$  f" ]; then                 hash=$  (git hash-object "$  path/$  f" -w)                 type=blob                 mode=100644                 if [ -x "$  path/$  f" ]; then                     mode=100755                 fi                 treeData="$  (printf '%s\n%s %s %s\t%s' "$  treeData" $  mode $  type $  hash $  f)"             elif [ -d "$  path/$  f" ]; then                 # recurse                 treeData="$  (printf '%s\n%s' "$  treeData" "$  (createSubtreeRec $  fullpath)")"                 #echo "$  treeData" >&2             fi         done         # ignore empty dirs         if [ "$  treeData" ]; then             # remove leading \n             treeData="$  {treeData:1}"             #echo "$  treeData" >&2             hash="$  (echo "$  treeData" | git mktree)"             printf '040000 tree %s\t%s' $  hash "$  (basename "$  path")"         fi     elif [ -f "$  path" ]; then         hash=$  (git hash-object "$  path" -w)         type=blob         mode=100644         if [ -x "$  path" ]; then             mode=100755         fi         printf '%s blob %s\t%s' $  mode $  hash "$  (basename "$  path")"     fi     #echo "" >&2 }  # createSubtree <workdir> <path> # Creates a subtree starting in <workdir> with the names in <path> as recursive trees, # Use to get a tree that does not contain <workdir> but contains all of <path>  #   and all contents beneath it. # Prints the top tree's hash on standard output. function createSubtree () {     local workdir="$  1"     local path="$  2"     # Get tree from     if [ "$  path" != "" ]; then         local entry=$  (createSubtreeRec "$  workdir/$  path")     else         local entry=$  (createSubtreeRec "$  workdir")     fi     if [ "$  entry" ]; then         while [ "$  path" ] && [ "$  path" != "." ] ; do             local hash=$  (echo "$  entry" | git mktree)             path="$  (dirname "$  path")"             local entry="$  (printf '%s %s %s\t%s' '040000' tree $  hash $  (basename "$  path"))"         done         printf '%s\n' $  hash     fi } 

createSubtreeRec outputs the full tree data line because it can sometimes output blobs.

This code is a significant part of my runtime, so any performance improving observations would be appreciated.

Part of me just wants this available online as it would have helped me out, and I can’t find any git builtin commands for this.

Starting and Finishing time of Tree Edge, Cross Edge, Back Edge

There is a certain relationship, when DFS search for a tree traversal occurred. Say if an UV traversed. Then relation between it’s start time and end time is enter image description here

Now, my question is if u start early, then should finish early. Right? Then how start[u]end[v], means u finishes late. How is it possible?? Similar for back edge and forward edges too. Only cross edges u start time and finish time both in late. So, it is matching my viewpoint.Plz explain:

http://www.cs.yale.edu/homes/aspnes/pinewiki/DepthFirstSearch.html

Manual Regression Tree using Python

I wrote a code to create a regression tree for a synthetic train data of size Np. The idea is, first I have the source node (which consists of all set of points) represented as a dictionary {'points':..., 'avg':..., 'left_node':..., 'right_node', 'split_point': }. The left and right nodes are the leafs after the splitting process of the whole data (source). split_point is for information about the best split. Then I loop to get deeper tree with maximum number of nodes specified before, also I set that a node must have more than 5 points in order it can be split.

This way, If I want to predict a point (x',y'), I can just start from source node source and check which region the point lies (left_node or right_node), ..and then continuing down the tree. Because all left_nodes and right_nodes values have the same structure as source….

Also, the form function is used to find the best split, the best split is the one with the smallest form(reg_1, avg1, reg_2, avg2). This is a greedy algorithm to find the best split.


I would like to know better ways to perform it..without external modules. But this is intended to be taught to high school students.


Full code:

import math import random import matplotlib.pyplot as plt   def form(region_1, av1, region_2, av2):     return sum([(i[1]-av1)**2 for i in region_1]) \            + sum([(i[1]-av2)**2 for i in region_2])  Np = 400 x_data = [abs(random.gauss(5, 0.2) + random.gauss(8, 0.5)) for i in range(Np)] y_data = [abs(random.gauss(10, 0.2) + random.uniform(0, 10)) for i in range(Np)] value = [abs(random.gauss(4, 0.5)) for i in range(Np)]  data = [((i,j), k) for i,j,k in zip(x_data, y_data, value)]  fig, ax = plt.subplots()  ax.plot(x_data, y_data, 'o')  fig.show()   ###### Splitting from the source node (all data)  source = {'points': data, 'avg': sum([i[1] for i in data])/Np, \           'split_point': None, 'left_node': None, 'right_node': None} forms = []  for x in x_data:     var = x     region_1 = [j for j in data if j[0][0] <= var]     region_2 = [j for j in data if j not in region_1]      if len(region_1) > 0 and len(region_2) > 0:          av1 = sum([i[1] for i in region_1])/len(region_1)         av2 = sum([i[1] for i in region_2])/len(region_2)          f = form(region_1, av1, region_2, av2)         leaf_1 = {'points': region_1, 'avg': av1}         leaf_2 = {'points': region_2, 'avg': av2}         forms.append( (leaf_1, leaf_2, ('x', var), f) )  for y in y_data:     var = y     region_1 = [j for j in data if j[0][1] <= var]     region_2 = [j for j in data if j not in region_1]      if len(region_1) > 0 and len(region_2) > 0:          av1 = sum([i[1] for i in region_1])/len(region_1)         av2 = sum([i[1] for i in region_2])/len(region_2)          f = form(region_1, av1, region_2, av2)         leaf_1 = {'points': region_1, 'avg': av1}         leaf_2 = {'points': region_2, 'avg': av2}         forms.append( (leaf_1, leaf_2, ('y', var), f) )   sorted_f = sorted(forms, key = lambda x: x[3]) best_split = sorted_f[0] source['split_point'] = best_split[2] source['left_node'] = best_split[0] source['right_node'] = best_split[1]   ##### Splitting from the 2 leafs and so on..  leafs = [source['left_node'], source['right_node']]  all_nodes = [leafs[0], leafs[1]]  max_nodes = 1000  while len(all_nodes) <= max_nodes:     next_leafs = []     for leaf in leafs:         if (len(leaf['points']) > 5):              xx = [i[0][0] for i in leaf['points']]             yy = [i[0][1] for i in leaf['points']]             rr = [i[1] for i in leaf['points']]             vv = [((i,j), k) for i,j,k in zip(xx, yy, rr)]             forms = []              for x in xx:                 var = x                 region_1 = [j for j in vv if j[0][0] <= var]                 region_2 = [j for j in vv if j not in region_1]                  if len(region_1) > 0 and len(region_2) > 0:                      av1 = sum([i[1] for i in region_1])/len(region_1)                     av2 = sum([i[1] for i in region_2])/len(region_2)                      f = form(region_1, av1, region_2, av2)                     leaf_1 = {'points': region_1, 'avg': av1}                     leaf_2 = {'points': region_2, 'avg': av2}                     forms.append( (leaf_1, leaf_2, ('x', var), f) )              for y in yy:                 var = y                 region_1 = [j for j in vv if j[0][1] <= var]                 region_2 = [j for j in vv if j not in region_1]                  if len(region_1) > 0 and len(region_2) > 0:                      av1 = sum([i[1] for i in region_1])/len(region_1)                     av2 = sum([i[1] for i in region_2])/len(region_2)                      f = form(region_1, av1, region_2, av2)                     leaf_1 = {'points': region_1, 'avg': av1}                     leaf_2 = {'points': region_2, 'avg': av2}                     forms.append( (leaf_1, leaf_2, ('y', var), f) )              sorted_f = sorted(forms, key = lambda x: x[3])             best_split = sorted_f[0]             leaf['split_point'] = best_split[2]             leaf['left_node'] = best_split[0]             leaf['right_node'] = best_split[1]              print(leaf['split_point'])              next_leafs.append(leaf['left_node'])             next_leafs.append(leaf['right_node'])              print("\n")      leafs = next_leafs     all_nodes.extend(leafs)     if len(leafs) == 0:         break 

Finding minimum spanning tree with O(|V|)

Given an undirected weighted graph $ G(V,E)$ , where the number of edges is $ |V|+10$ , how can I find the minimum spanning tree of $ G$ in $ O(|V|)$ ?

Kruskal’s algorithm is out of the question, since sorting alone is $ O(|V|\log |V|)$ , so I thought maybe using Prim’s algorithm with minimum binary heap, but still – every iteration will cost $ \log |V|$ for updating vertices keys in the heap, so altogether it’s $ |V|\log |V|$ .
I know that the key here is to use the fact that $ |E|=|V|+10$ , so I start thinking maybe removing the 11 edges with the biggest weights, as long as the graph stays connected, but that’s obviously a bad idea since it’ll – again – require sorting.
I just can’t figure it out. Any help would be greatly appreciated.