Help me understand Inorder Traversal without using recursion

Start with the recursive algorithm (pseudocode) : traverse(node): if node != None do: traverse(node.left) print node.value traverse(node.right) endif This is a clear case of tail recursion, so you can easily turn it into a while-loop. traverse(node): while node != None do: traverse(node.left) print node.value node = node.right endwhile You’re left with a recursive call. What … Read more

How to convert to D3’s JSON format?

There’s no prescribed format, as you can usually redefine your data through various accessor functions (such as hierarchy.children) and array.map. But the format you quoted is probably the most convenient representation for trees because it works with the default accessors. The first question is whether you intend to display a graph or a tree. For … Read more

Hierarchical/tree database for directories path in filesystem

Here’s a quick closure table example for SQLite. I’ve not included the statements for inserting items into an existing tree. Instead, I’ve just created the statements manually. You can find the insert and delete statements in the Models for hierarchical data slides. For the sake of my sanity when inserting the IDs for the directories, … Read more

What’s the difference between ordering and sorting?

An “ordering” is basically a set of rules that determine what items come before, or after, what other items. IE: the relative order items would appear in if they were sorted. For collections that enforce an ordering, that ordering is generally specified in terms of comparison operators (particularly <), interfaces (a la Java’s Comparable<T>), or … Read more

Height of a binary tree

if (node == null) { return 0; } The children of leaf nodes are null. Therefore this is saying that once we’ve gone past the leaves, there are no further nodes. If we are not past the leaf nodes, we have to calculate the height and this code does so recursively. return 1 + The … Read more

Plot trees for a Random Forest in Python with Scikit-Learn

Assuming your Random Forest model is already fitted, first you should first import the export_graphviz function: from sklearn.tree import export_graphviz In your for cycle you could do the following to generate the dot file export_graphviz(tree_in_forest, feature_names=X.columns, filled=True, rounded=True) The next line generates a png file os.system(‘dot -Tpng tree.dot -o tree.png’)