c,algorithm,tree,binary,binary-tree

You should be doing something like: int total_depth(tree_t *tree, int accum) { if (tree == NULL) { return 0; } return accum + total_depth(tree->left, accum + 1) + total_depth(tree->right, accum + 1); } total_depth(root, 0); ...

python-3.x,recursion,tree,member

Be very, very cautious of this: def __init__(self, value, parent=None, children=[]): and this: def insertChildren(self, children=[]): The initial value -- the list object created by [] -- is a single object which is shared. Widely. You are using this single, shared, default list object widely. You may want to use...

The cause of a such behavior is that you use scope variables out of the scope. You must not use the pointer that points to the scope variable out of that scope. Scope variables exists only withing the scope were they were declared. If decide to access a scope variable...

This is my solution: def print_tree(current_node, indent="", last='updown'): nb_children = lambda node: sum(nb_children(child) for child in node.children) + 1 size_branch = {child: nb_children(child) for child in current_node.children} """ Creation of balanced lists for "up" branch and "down" branch. """ up = sorted(current_node.children, key=lambda node: nb_children(node)) down = [] while up...

It's possible in a variant of B+ tree called PO-B+ tree. In this "preparatory operations B+ tree" the number of keys in a node may be between n-1 and 2n+1 rather than n and 2n in the usual B+-tree (quoted from the paper). For delete operation (called PO-delete in the...

algorithm,data-structures,tree,binary-search-tree

In the general case, your algorithm needs perform a series of tree manipulations in the form of sub-tree rotation (as described in @Quicky's answer). The algorithm should look like this: While node_to_be_root is not the root of the whole tree: Rotate the sub-tree where the node_to_be_root is the pivot and...

My Prolog is slightly rusty, but I believe that this should do it: node(Left, Right). trav(node(Left, Right), L) :- trav(Left, L1), trav(Right, L2), append(L1, L2, L). trav(X, [X]) :- X \= node(A, B). Intuitively, trav(Left, L1) says traverse the left subtree, storing each element in L1. trav(Right, L2) says traverse...

algorithm,data-structures,tree,binary-tree,binary-search-tree

I'd call your understanding not quite correct. The big-O notation does not say anything about an exact amount of steps done. A notation O(log n) means that something is approximately proportional to log n, but not neccesarily equal. If you say that the number of steps to search for a...

There are a number of problems in your code: You use member of pointer -> operator on member variables operand1 and operand2 You need two different types in template arguments to initialize object with different argument types. Classes/constructors don't autodetect types like functions do. It means that you can not...

To get the selected item and all its attributes and values, you can use the item method: def selectItem(a): curItem = tree.focus() print tree.item(curItem) This will output a dictionary, from which you can then easily retrieve individual values: {'text': 'Name', 'image': '', 'values': [u'Date', u'Time', u'Loc'], 'open': 0, 'tags': ''}...

c,string,algorithm,data-structures,tree

If your C standard library is GNU or *BSD, then you probably have asprintf available. You may need to enable a feature test macro to use it, though. If you don't have asprintf available, it can easily be defined in terms of the C standard vsnprintf function. asprintf returns the...

If you would like to expand the path from root to node with specific name, you could use some algorithm to get the path, e.g. depth-first with stack where you store the path. Here is the sample of function which encapsulates recursive function and returns the array with indexes of...

data-structures,tree,heap,binary-search-tree,avl-tree

A heap may have better insert and merge times. It really depends on the type of heap, but typically they are far less strict than an AVL because they don't have to worry about auto balancing after each operation. A heap merely guarantees that all nodes follow the same style...

algorithm,graph,tree,minimum-spanning-tree

For any connected graph, the spanning tree always contains n-1 edges where n is the number of nodes in the graph. So you will have to remove all the remaining edges. (If I have understood your question correctly) Even for disconnected graphs, the number of edges in a spanning tree...

scala,tree,sum,pattern-matching,case-statement

This works. @marios answer led me to the right path, even though his implementation had a bug and didn't work. def leafSum(lst: List[Any]): Int = { lst.foldLeft(0) { case (sum, node: List[_]) => sum + leafSum(node) case (sum, leaf: Int) => sum + leaf } } ...

json,mongodb,split,tree,talend

For those who are interrested, I solved this issue by creating my own MongoDBOuput in a tJavaRow. In this way, I am more able to control the creation of my JSON schema. For example (in a tJavaRow): /*Get the MongoDB connection*/ DB db = (DB)globalMap.get("db_tMongoDBConnection_1"); /*Get the collection*/ DBCollection coll...

jquery,d3.js,tree,collapse,expand

You could hide children of the node as follows: function collapseSingle(node) { if (node.children) { node._children = node.children; node.children = null; } } Now, if you would like to show the childrens of node you could do this: function expandSingle(node) { if (node._children) { node.children = node._children; node._children = null;...

objective-c,recursion,path,tree

Say the tree is represented like this: @interface TreeNode : NSObject @property(weak,nonatomic) TreeNode *parent; @property(strong,nonatomic) NSArray *children; @end The lineage (which is what you're looking for) of any node, is a list of nodes from the root to the node. This can be defined recursively like this: - (NSArray *)lineage...

Your assumption: the instantiating of another BinaryTree would also require reserving memory space to store all non-static methods of the class BinaryTree. is incorrect. Class instance methods do not take up space with each new instance of a class. The only memory space taken up by an instance is its...

algorithm,tree,binary-search-tree,complexity-theory

Your current inorder traversal using recursion to perform the task. That makes it difficult to run more than one at the same time. So, first I would re-write the method to use an explicit stack (example here in C#). Now, duplicate all of the state so that we perform traversals...

string,algorithm,search,graph,tree

It's an interesting problem; usually one would imagine a single tree being searched for a variable set of strings. Here the situation is reversed: the set of strings is fixed and the tree is highly variable. I think that the best you can do is build a trie representing the...

Your summation functions are altering the tree: int sommachiavidestra(node*& tree){ if (tree == nullptr){ return 0; } tree = tree->right; return sommatuttechiavi(tree); } will set the parameter to its own right subtree. Since you recurse when checking the "property", you will reach a point where after (sommachiavisinistra(tree)*k) < sommachiavidestra(tree), tree...

I guess you're looking to organize the whole array so items are children of some states. Run the following snippet to get a JSON-serialized result to check it (click show code snippet to see the code and run it!): var arr = [{ id: "1", state: "1", ndi: "1558.3045298", children:...

This example is far from production ready, but it should contain everything you need everything you need for implementing the full solution. This only searches for lines only, does not know which attributes it needs to look for on other kinds of geometry and hasn't got any kind of error...

If you add a note to an empty BST, the execution will be: bool BST::add(int k, int x, int y) { return add(root, k, x, y); } As root is NULL, the following will happen in add(root, k, x, y): bool success; if (n = NULL) { // <=== OUCH...

c,parsing,recursion,tree,binary-tree

The problem is that you need the recursive call to return both the newly created node and the updated input pointer. There are various ways of doing this, but the easiest one in C is to pass the input pointer by reference; or, in other words, pass a pointer to...

Actually I found a way to achieve this functionality. <h:form id="frmHierachiManage" styleClass="treeForm"> -- tree inside this form </h:form> then in the backing bean, RequestContext.getCurrentInstance().update("frmHierachiManage"); this updated the tree view....

You just need to rewrite in the another direction: open import Relation.Binary.PropositionalEquality insert : ∀ {A n} -> A -> T A n -> T A (suc n) insert x empty = leaf x insert x (leaf y) = bal (leaf y) (leaf y) insert x (bal l r) =...

In PHP you can try: $foo = // your flat array of associative arrays // add the top level nodes to an array $result = array(); foreach ($foo as $node) { if ($node['parent-id'] === '') { $node['children'] = array(); array_push($result, $node); } } // recursively iterate this array adding the...

The point you are missing is nodes.pop(0) pops the 0th element. So you are wrong here: Then as the stack would only pop out the last element of the list, then... Imagine a binary tree: 1 / \ 2 3 / \ / \ 4 5 6 7 / \...

Here's a simple approach that passes the recursion off to php: $tree = array(); foreach($words as $word) { $characters = array_reverse(str_split($word)); $temp = array(); foreach($characters as $index => $character) { if($index == 0) { $temp[] = getPoints($word); } $temp = array( $character => $temp ); } $tree = array_merge_recursive($tree, $temp);...

symfony2,doctrine2,tree,doctrine-extensions,stofdoctrineextensions

I found problem, when i delete a entity by $em->remove method, doctrine extension assume that onDelete=cascade for entity & change lft & rgt values of tree, then run query for removing of entity(and all children), but my entity have onDelete=restrict, then lft & rgt values are updated, but children is...

I've just realized my BIG mistake in the code and I'll just answer myself since no one had found the answer. The error lies in this piece of code: for(tmp = (*T)->children; tmp->brother != NULL; tmp = tmp->brother) { DeleteTree(&tmp); } First of all Ami Tavory was right about the...

var tree = {}; var addTree = function(aggregateId) { if (aggregateId) { var arr = aggregateId.split('|'), arr.reduce(function(node, id) { if (!node.id) { node.id = id; node.children = {}; } return node.children; }, tree); } }; addTree('1|100376|100377|100378'); addTree('1|100376|100377|100379|100380'); console.log(JSON.stringify(tree)); // {"id":"1","children": // {"id":"100376","children": // {"id":"100377","children": // {"id":"100379","children": // {"id":"100380","children":{}}}}}} However, I...

Something like this will copy your Tree: def copyTree(t:Tree):Tree = { t match { case EmptyNode => EmptyNode case Node(left, right, value) => Node(copyTree(left), copyTree(right), value) } } ...

May be a basic tree structure like this will work...(this is just basic)... void Main() { Tree t = new Tree<string>(); //replace string with your data type in this generic list //individually Node<string> nd1=t.AddNode("level 1"); Node<string> nd2=nd1.AddNode("level 2"); Node<string> nd3=nd2.AddNode("level 3"); //in a loop var lst = new List<string>{"Level 1",...

Select colD from tableName where colB='2'; Isn't the above query sufficient ? Update If you need this to be done in java then : ResultSet rs=getAllDataInResultSet();//this method will return from stored procedure List<int> resultList=new ArrayList<>(); while(rs.next()){ int colB=rs.getInt(2); if(colB==2){ resultList.add(rs.getInt(4)); } } logger.debug(resultList); //logging the final Result list Output :...

We found that in the Tree mapping file, we had to name the left: and right: columns as lft: and rgt:, identically to the examples on the github repository for the yaml mappings. fields: lft: <---- type: integer nullable: false options: unsigned: false gedmo: - treeLeft rgt: <----- type: integer...

ComboBox Items contains objects, which are pretty dumb. The first thing you should do is to create a class, maybe like this: class ComboItem { public string Text { get; set; } public int Level { get; set; } public ComboItem (string text, int level) { Text = text; Level...

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace RedBlackTree { class RBTree { public class node { public node right, left, next, back,last;//for traversing the public int id;//for regular implementation int day, month, year;//for root @ weeks int hour, min;//for shipment...

algorithm,graph,tree,runtime,big-o

Since everything is still connected and only one edge has been removed, then most (and maybe all) of the spanning tree remains the same. Attempt to construct the same minimum spanning tree, and if the edge that was removed was part of the spanning tree, grab the next smallest edge...

haskell,recursion,tree,functional-programming,binary-tree

I think the problem is you're naming giving the inner nodes the same names so connectOutside connects the first names it finds (which happen to be the last nodes in your tree). You can solve this by giving each node a unique name depending on its position: diagTree :: Show...

I found the solution to my question. It turns out that nodes don't have parent, position (x, y coordinates), and depth attributes before tree.nodes(root) is called, which calculates all of the above mentioned attributes. So what I had to do is call that function before I call collapse function. After...

angularjs,tree,grid,angular-ui-grid

I think this may be the alignment issue that was fixed this morning, which occurs when you have filters. The treeView appears to be working correctly today. If you have an issue that is different than that, could you provide a bit more detail - your description is somewhat unclear...

java,data-structures,graph,tree,edge

You need to add a method for disconnecting a child from a parent node. That would look something like this: private void disconnectChild(Node child) { children.remove(child); } You would then call this method from your disconnect() method like so: private void disconnect() { if (parent != null) { parent.disconnectChild(this); parent...

The result is a sum of the node's value and the computed values of both subtrees: i=tree->data + countQuantity(tree->left) + countQuantity(tree->right) ...

java,algorithm,tree,position,traversal

To remove the need for reihe (and I'm assuming it's not english since it makes no sense as a variable name to me). I've passed the variable k as a return value. When it reaches 0, I return the current value and stop searching. int valueAtPosition(int k) { if(this.left!=null k...

r,tree,survival-analysis,rpart

The survival data are scaled internally exponentially so that the predicted rate in the root node is always fixed to 1.000. The predictions reported by the predict() method are then always relative to the survival in the root node, i.e., higher or lower by a certain factor. See Section 8.4...

c#,lambda,path,tree,expression-trees

So the starting place is creating an expression visitor. This lets us find all of the member accesses within a particular expression. This leaves us with the question of what to do for each member access. So the first thing is to recursively visit on the expression that the member...

c,tree,artificial-intelligence,minimax

Your buildGameTree should be: struct Node *buildGameTree(){ struct Node *cube= calloc(1,sizeof(struct Node)); cube->numCubes = M; cube->left = NULL; cube->right = NULL; if (cube->numCubes >= 1){ cube->numCubes = cube->numCubes - 1; cube->left = buildGameTree(); } if (cube->numCubes >= M){ cube->numCubes = cube->numCubes - M; cube->right = buildGameTree(); } return (cube); }...

If the your input array is already sorted(prepared) by date and name for printing: foreach ($myarray as $item) { $date = explode('-', $item['date']); if (empty($year) || $year != $date[0]) { $year = $date[0]; print "{$year}\n\r"; } if (empty($month) || $month != $date[1]) { $month = $date[1]; print "\t" . strtoupper(date("M",...

In data mining, there is a multi-way trade-off between the number of features that you use, your accuracy, and the time it takes to generate a model. In theory, you'd want include every possible feature to boost accuracy; however, going about data mining in this way guarantees lengthy model generation...

extjs,tree,local-storage,store

Just move the creation of tree store inside initComponent: Ext.define('Eits.view.OrgTreeView', { extend: 'Ext.tree.TreePanel', requires: ['Eits.model.OrgTreeModel'], width: '100%', region: 'center', border: true, initComponent: function() { this.store = Ext.create('Ext.data.TreeStore', { fields : Eits.model.OrgTreeModel.FIELDS, autoLoad: false, root: { id: 'rootNode', objectId : 'rootNode', leaf: false, expanded: false, text: localStorageProvider.get('name'), iconCls: 'mts-Tree-Node', }, proxy:...

java,algorithm,data-structures,tree,trie

One reason this program get TLE (keep in mind that time constraint is 1 sec): Each time you create a Batman object, it will create an array with length [26], and it is equivalence to adding a loop with n = 26. So, you time complexity is 26*5000*5000 = 650000000...

Why didn't the separation function solve your problem? You get two nodes as params to the separation function. If you set nodeSize([1, 200]) and calculate the actual width of both nodes inside the separation function, you could add an appropriate separation. .separation(function(a, b) { var totalWidth = a.width + b.width;...

This is a famous problem - dynamic order statistcs by tree augmentation. You basically need to augment your nodes so that when you look at a child pointer, you know how many children are in the child's subtree at time O(1). It's easy to see that this can be done...

def buildTrees(data: Seq[Mapping]): Seq[Node] = { def attachToParents(newChild: Mapping, parents: Seq[Node]): Seq[Node] = { for (parent <- parents) yield { val attachedChildren = attachToParents(newChild, parent.children) if (newChild.parents.contains(parent.name)) parent.copy(children = Node(newChild.name) +: attachedChildren) else parent.copy(children = attachedChildren) } } @tailrec def helper(xs: Seq[Mapping], accu: Seq[Node]): Seq[Node] = xs match { case...

First of all let's observe that if you will traverse some edges multiple times in the optimal solution, then all these edges will have same reward (otherwise it's more profitable to traverse the edge with bigger reward more times). So without loss of generosity we can say that you will...

Not with immutable case classes. It is a circular dependency: you need the parent to create the children, but you also need the children to create the parent. On the other hand most tree traversal algorithms don't really need the parent as the parent is usually on the stack...

algorithm,data-structures,tree,binary-tree,binary-search-tree

Rather than jumping right into an algorithm that works here, I'd like to give a series of observations that ultimately leads up to a really nice algorithm for this problem. First, suppose that, for each node in the tree, you knew the value of the largest and smallest values in...

You can do a binary search to find the key you need within one node. Or, better, store all keys and links within a node in a binary search tree....

java,parsing,tree,abstract-syntax-tree,lr

You don't need to build a node on every reduction, and the nodes you do build don't need to include every symbol being reduced. Nor do the reduced symbols need to appear in the same order as the parse. In many cases, an AST is a simplification of the full...

c++,algorithm,data-structures,tree

There is nothing wrong with this code. According to wikipedia: 'These constraints enforce a critical property of red–black trees: that the path from the root to the furthest leaf is no more than twice as long as the path from the root to the nearest leaf. The result is that...

Your error is in the initialization of your Node: you don't alloc the memory buffer for the data. You make it point to your parameter, that is on the stack and not on the heap. As soon as your createNodefunction end, the stack is emptied and your parameter (so your...

You could keep a class variable and use it for ordinal ids: class Node(object): _id = 0 def __init__(self): self._id = Node._id Node._id += 1 It also has the benefit that your class will be able to know how many objects were altogether created. This is also way cheaper than...

Classical B-trees constrain key counts for non-root nodes to lie between d and 2d for some d. This means that merging of nodes is only possible if an underflow has already occurred and the other node involved in the merge has minimum occupancy. Together with the separator key pulled from...

To implement a trie, you'll want a way to turn a letter into a reference to the next node. There are 2 obvious choices: a array Node[] nodes = new Node[26]; (assuming English language) a Map<Character, Node> map = new HashMap<Character, Node>(); The array is the classic C approach, but...

text,svg,d3.js,tree,rectangles

It depends on how you want your text formatted inside the bar. I'll go for a naive way. You want to make the bar larger, and the amount of extra height depends on how long your string actually is. Find out what your max width for a bar is, and...

I finally got around to making a sample for you. This should be a nicely scalable recursive solution. :) static void Main(string[] args) { Node root = new Node("/"); AddNode("New Text Document.txt", root); AddNode("New folder/", root); AddNode("New folder/README.txt", root); Console.ReadKey(); } public class Node { public Node() { Nodes =...

php,recursion,yii,tree,catalog

For other folks who could be interested in this issue, I've solved it in a such way: In category controller view action I call: $model = $this->loadModelSlug($slug); $organizationsList = Organization::getOrganizationsFromSubcategories($model); In Organization model: public static function getOrganizationsFromSubcategories($category) { $childCategoriesIds = OrganizationCategory::getChildCategoriesIds($category); $criteria = new CDbCriteria(); $criteria->addInCondition('organization_category_id', $childCategoriesIds); $result =...

Well, I finally sorted it out, thanks to Krzysztof's hints. Now the nodes with children are handled correctly and attribute leaves are where they should be: private DefaultMutableTreeNode buildTreeNode(Node rootNode) { DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode( rootNode.getNodeName()); if (rootNode.hasAttributes()) { NamedNodeMap attributes = rootNode.getAttributes(); for (int j = 0; j...

javascript,jquery,dom,dynamic,tree

Try this: var json = { Asia: [{ regionList: [{ regionName: "Eastern Asia", Countrylist: [{ countryName: "China", subCountryList: [{ subCountryName: "Southern China" }] }, { countryName: "Hong Kong" }] }, { regionName: "Southern Asia", Countrylist: [{ countryName: "India" }, { countryName: "Pakistan" }] }] }] }; var html = '';...

You needed to go through all of the subRegions and add them. Secondly, you needed to add an event listener to all of the regions with subRegions. I didn't add the plus/minus images, but you can add those into the event listener with the hide()/show() functions, respectively. var data =...

javascript,d3.js,internet-explorer-8,tree,wrap

Hy, I think, you can't create next line with excess text. However, you can use tspan element inside text element like: <text y="10"> <tspan x="10">tspan line 1</tspan> <tspan x="10" dy="15">tspan line 2</tspan> <tspan x="10" dy="15">tspan line 3</tspan> </text> see tspan element...

Just remove the xtype on the second treecolumn. It will default to gridcolumn, so it will look like a normal grid column.

As with most things functional, the answer is recursion. It's in fact tremendously easier to do functionally than it would be to do by mutating a bunch of lists of lists in java. You just define a function that converts a single ArrayList into a clojure list, and then have...

Yes there is, but it will also require adding some more data to treeNode, a pointer to the list node (if such exist). Now, the idea is once you have found where to add the new node (v), and let's say it is a son of some node u. You...

c++,data-structures,tree,binary-tree,binary-search-tree

The main work is being done in getMaxWidthRecur. It's initially given the parameter level = 0. The level parameter is incremented by 1 whenever we recurse down one level in the tree. The recursion will hit each node in the tree exactly once, and for each node in the tree,...

here are the new versions of the classes, with the methods that you needed. import java.util.ArrayList; import java.util.List; public class Node { public Node parent;//the parent of the current node public List<Node> children;//the children of the current node public Object info; public static int maxNrOfChildren;//equal to the k-arity; public Node...

Are you sure the format=1 is correct? According to documentation - for named internal nodes we will use format 1 Are you sure your newick tree has named internal nodes? If not, try without passing any value to the format argument. Also, please make sure that the filename is either...

python,list,python-2.7,tree,numbers

You can use itertools.combination to get the desire pairs and use izip to zip your lists and compare the elements in same index. Also as a more elegant way you can put your lists within a dictionary like following : d={ 'list_1':[13579875, 25732, 3541, 56732, 1567, 20546, 10, 68971], 'list_2'...

c#,c++,boost,tree,nearest-neighbor

What you are looking at is a C++ inlined function template and it is actually defined at the top of the header file you linked (thus the util:: namespace rather than boost:: namespace). In C#, it looks like you could implement this logic in a static function if you lift...

You are destroying twice the children member: first time in the for loop, the second time after the loop. You might want to write your for loop like that: for (tmp = tree->brother; tmp != NULL; tmp = tmp->brother) { delete_tree(tmp); } ...

I've played around and here is the result nonechar = 'N' spacechar = '_' solution = [[6], [0, 7], [None, 3, None, 8], [2, 5, None, 9], [1, None, 4, None, None, None], [None, None, None, 4],[None, 3]] for i in range(1, len(solution)): for j in range(len(solution[i-1])): if (solution[i-1][j] ==...

The screenshot shows that the tree command is setting the foreground color, without resetting it. The ls command does reset colors, sending \e[0m (where \e is the escape character). Call it a bug in tree. There is no general/portable method for restoring the original colors before a program is run....

Have a loop that for each node, visits the first k/2 subtrees recursively. After that returns, access the current node, then within a loop, recursively visit the remaining subtrees.

You are correct, you need to traverse the tree, which can be elegantly achieved in SML by using pattern matching. You will want to case on the input tree, if it is Empty then simply return Empty. If it is a Node, then you will want to recursively convert the...

You can make an iterator look nice with something like this: class TreeIter: def __init__(self, parametersIfAny): code godes here def __iter__(self): return self def __next__(self): code that makes the iteration class Tree: def __iter__(self): return TreeIter(parametersIfAny) Then you can invoke it like this: tree = Tree() for node in tree:...

First of all, I modified the toString() method of the Trie to get some better debug information. The only important rows to achieve what you are asking are these in _get method: V result = t._get(key.deleteCharAt(0), ++level); return result == null ? entry.value : result; The trie now prefers current...

Try out this code. It splits the array recursively. function split(arr, n) { if(n <= 1) return [arr]; var partLength = Math.ceil(arr.length/n), part1 = arr.slice(0, partLength), result = split(arr.slice(partLength), n - 1); result.unshift(part1); return result; } function splitTree(arr, m) { if(m.length < 1) return arr; var result = split(arr, m[0]);...

algorithm,graph,tree,runtime,big-o

Don't know if your algorithm is correct, but it doesn't seem O(|V|) at least, because getting the "smallest edge not in T" of a vertex cannot be done in O(1). The most usual way to add an edge e=(u, v) into a MST T is: Run a BFS in T...

algorithm,tree,binary-tree,binary-search-tree,graph-algorithm

I guess this should do the trick: traverse(BinaryTree *root) { if (!root) return; cout << p->data << " "; if (root->left ) traverseL(root->left ); //special function for outer left if (root->right) traverseR(root->right); //special function for outer right } traverseL(BinaryTree *p) { cout << p->data << " "; if (root->left )...