Menu
  • HOME
  • TAGS

Yii 1. Get products from categories AND their subcategories [Unlimited nesting]

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 =...

B-Tree deletion in a single pass

algorithm,tree,b-tree

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...

Specifying nodeSize for each node individually in D3.js tree layout

javascript,d3.js,tree,spacing

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;...

How to change the datatype of an existing tree in SML?

recursion,tree,sml,smlnj

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...

Scala sum of all elements in the leaves of a tree using pattern matching

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 } } ...

Using Diagrams library in haskell (draw binary trees)

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...

Convert Directory Path to JSON Directory Tree Representation

c#,json,tree,filepath

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 =...

Tree searching algorithm

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...

Adding a new branch to a tree then adding the new leaf to the right place in a linked list in an efficient way

c,algorithm,tree,binary-tree

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...

Making a very basic binary tree in Scala

scala,tree,binary-tree

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...

Function that return average depth of a binary search tree

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); ...

Transform flat array of objects intro tree [closed]

php,arrays,parsing,tree

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...

how to auto-adjust the height of an rectangle to contain the text inside it in d3 tree

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...

How to pass variable filename to python ete?

python,variables,tree

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...

K-Ary Tree Implementation in Java: how to?

java,algorithm,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...

K-Ary Tree and Symmetric Search/Visit in Java

java,algorithm,tree

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.

recursively editing member variable: All instances have same value

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...

RedBlack Tree Implementation

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...

To print the boundary of Binary Tree

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 )...

Java: make prefix tree remember last value that was not null

java,tree,prefix,trie

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...

Update minimum spanning tree if edge is removed

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...

ExtJS Put link in tree column of a tree panel

javascript,extjs,tree,extjs5

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

Need some help making a php search tree

php,tree

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);...

Python access mother class fields

python,tree,iterator,instance

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:...

Designing a more efficient tree

java,algorithm,recursion,tree

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...

Navigate an NLTK tree (follow-up)

python,tree,nlp,nltk

I usually use the subtrees function in combination with a filter for this. Changing your tree slightly to show that it only selects one of the NP's now: >>> tree = ParentedTree.fromstring("(S (NP (NNP)) (VP (VBZ) (NP (NNS))))") >>> for st in tree.subtrees(filter = lambda x: x.label() == "NP" and...

Angular ui-grid. Error in example?

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...

C - Nary Tree: error while appending a new child to the tree

c,tree,children,appendchild

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...

Need to convert a Result Set to some data structure

java,sql,tree,resultset

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 :...

Print in tree format in smart loop

php,tree

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",...

Prefix math expressions array to parse tree - recursion to move with array

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...

What is the most efficient way to build an unsorted binary tree in java?

java,tree,binary-tree

public class BinaryTree{ private BinaryTree right; private BinaryTree left; private String data; public BinaryTree(String s){ data = s; right = null; left = null; } public void setLeft (BinaryTree l){ left = l; } public void setRight(BinaryTree r){ right = r; } } Your question suggests that the tree should...

Mutable tree to persistent tree

java,clojure,tree

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...

Tree traversal - inorder position

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...

Traverse a tree from root to all children in Objective-C

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...

Python and XML (LandXML) [closed]

python,xml,tree,iteration

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...

traversal method with a return value

tree,inorder

You want to use some kind of list structure to accumulate the data: void inorder(BSTNode r, List list) { if (r != null) { inorder(r.getLeft(), list); list.add(r.getData()); inorder(r.getRight(), list); } } Invoking the function with List list = new List(); inorder(bst, list); After inorder completes, list will contain the the...

How to find and check all dynamic child checkboxes in tree using jquery?

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 = '';...

Find path of given length with max weight or gain starting from source node

algorithm,graph,tree

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...

How to fetch the child of JSON data using jquery tree structure

javascript,jquery,json,tree

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 =...

How does this code work to find the Minimum Depth of Binary Tree?

python,algorithm,tree

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 / \...

Search B-Tree in O(log(t)*h)

data-structures,tree

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....

Statically balanced trees in Agda

tree,agda,dependent-type

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) =...

Binary red black tree, best way to walk back to root?

c#,algorithm,tree

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...

Recursive list split (javascript)

javascript,algorithm,tree

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]);...

Trie Data Structure in Finding an Optimal Solution

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...

Talend JSON structure

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...

using local storage saved value as a text in a root text

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:...

How to copy an object in Scala?

scala,tree,copy,binary-tree

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) } } ...

Use significant attributes only, or use full set of attributes to build J48 model after checking information gain?

tree,weka,c4.5,j48

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...

Trying to create an algo that creates a spanning tree with least number of edges removed from a unweighed graph

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...

First common element from different lists of numbers

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'...

Deletion from B-Tree - M=5

algorithm,tree,b-tree

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...

Refresh parent node from backing bean with primefaces tree

jsf,primefaces,tree

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....

'tree' and 'ls' change text color on Linux command line

linux,terminal,tree,ls

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....

Binary search tree intersection

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...

How to add items to ComboBox as tree list

c#,winforms,combobox,tree

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 a survival tree from the 'rpart' package in R to predict new observations

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...

d3 indented tree close other nodes with child and open only specific node

javascript,php,d3.js,tree

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...

JTree: How to add attributes of nodes as their own leaves?

java,xml,swing,tree,jtree

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...

python tkinter tree get selected item values

python,tkinter,tree,row

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': ''}...

Print a Pretty Tree

python-3.x,tree,bfs

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] ==...

How to use Expression Tree to safely access path of nullable objects?

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...

Mapping Nested Tree With Doctrine 2 and YAML

doctrine2,tree,doctrine,yaml

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...

C - deleting n-ary tree nodes

c,tree,delete,n-ary-tree

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); } ...

Given a BST, and a node in BST, make that node, as new root of the tree

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...

parent nodes value to be the sum of all its childrens

javascript,c#,recursion,tree

My strategy was to do a top-down traversal. Leaf nodes simply return their current value. Internal nodes recompute based on the sum of their children. function initialize(node) { // internal nodes get their total from children if (node.children.length > 0) { node.value = 0; for (var i = 0; i...

d3 tree very long text in indented tree how to put it in next line

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...

Update minimum spanning tree if edge is added

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...

How to free memory occupied by a Tree, C?

c,tree,free

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...

Can't find certain Boost library function

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...

Giving unique IDs to all nodes?

python,class,tree,nodes

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...

Expression tree data structure

c++,class,tree,expression

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...

prolog traverse nonstandard tree left to right

tree,prolog,tree-traversal

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...

Why would one use a heap over a self balancing binary search tree?

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...

Tree structure - incorrect children

c++,tree

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...

Does C have any tools for doing string addition?

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...

How to build a tree from a plain data structure

javascript,recursion,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:...

Building tree in Nim game

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); }...

Why tree is invalid?

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...

What is meant by complexity of O(log n)?

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...

Dynamically generated nested tree object from array

javascript,object,tree

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...

Maximum width of a Binary Tree using preorder traversal

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,...

Unhandled Exception with Binary Search Tree [closed]

c++,visual-c++,tree

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...

How to print a tree in Python?

python,tree,pretty-print

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...

dijit tree not able to get child from collapase tree

tree,dojo,children

We can use the getChildren function recursively to get all the children(till leaf nodes). onClick: function(item, node) { this.getChildItems(item); }, getChildItems: function(item) { dojo.forEach(this.model.store.getChildren(item), function(node) { console.log(node); this.getChildItems(node); }, this); } Thanks Srikant...

adding integers from each node of a tree

c,recursion,struct,tree

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) ...

Tree using recursive programming

c++,recursion,tree

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...

D3.js collapsable tree - visualise set number of levels

javascript,jquery,d3.js,tree

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...

collapse specific nodes on load in d3 tree

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;...

LR(1) parse straight to Abstract syntax 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...

Running trough a Tree in Java

java,recursion,tree

What is getTreeRules? Is that supposed to be getTreePaths? You need to call back into the function for every node. Edit for your last question in comment: Your flag list is accumulating because you're adding left and then keeping that when you go right. You could try something like: private...

cut the tree by removing edges

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...

Count the number of nodes in an AVL tree in a given range

c++,algorithm,tree

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...

how can an objects points on many other objects in JAVA?

java,pointers,tree,trie

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...

Find root of minimal height which is not BST

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...

How to organaze data in a tree-like structure?

c#,tree

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",...

How to build the tree if I know nodes and their parents?

scala,tree

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...