Depth-first post-order iteration of tree nodes
326811
def ipostorder(self):
        ''''''
        children = [self, ]
        seen = set()
        while children:
            cur_node = children[-1]
            if cur_node not in seen:
                seen.add(cur_node)
                children.extend(reversed(cur_node.children))
            else:
                children.pop()
                yield cur_node
135204
def traverse(self, predicate=lambda i, d: True,
                 prune=lambda i, d: False, depth=-1, branch_first=True,
                 visit_once=False, ignore_self=1):
        """"""
        return super(Tree, self).traverse(predicate, prune, depth, branch_first, visit_once, ignore_self)
865876
def iterations(self, parameter):
        """"""
        return numpy.arange(0, self.last_iteration(parameter), self.thinned_by)
1089448
def post_order(self):
        """"""
        for child in self.children:
            for node in child.post_order():
                yield node
        yield self
254208
function traverseDepthFirst(rootNode, options) {
  options = extend({
    subnodesAccessor: function(node) { return node.subnodes; },
    userdataAccessor: function(node, userdata) { return userdata; },
    onNode: function(node, callback, userdata) { callback(); },
    onComplete: function(rootNode) {},
    userdata: null
  }, options);

  var stack = [];
  stack.push([rootNode, options.userdata]);

  (function next() {
    if (stack.length == 0) {
      options.onComplete(rootNode);
      return;
    }

    var top = stack.pop();
    var node = top[0];
    var data = top[1];

    options.onNode(node, function() {
      var subnodeData = options.userdataAccessor(node, data);
      var subnodes = options.subnodesAccessor(node);
      async.eachSeries(subnodes,
        function(subnode, nextNode) {
          stack.push([subnode, subnodeData]);
          async.setImmediate(nextNode);
        },
        function() {
          async.setImmediate(next);
        }
      );
    }, data);
  })();
}
66272
def traverse_until_fixpoint(predicate, tree):
    """"""
    old_tree = None
    tree = simplify(tree)
    while tree and old_tree != tree:
        old_tree = tree
        tree = tree.traverse(predicate)
        if not tree:
            return None
        tree = simplify(tree)
    return tree
192649
synchronized void computeTrees() {
        boolean changed;
        try {
            createBuffers();
            do {
                switchBuffers();
                changed = computeOneLevel();
//System.out.println("Tree obj.   "+heap.idToOffsetMap.treeObj);
//if (changed) System.out.println("Next level  "+nextLevelSize);
            } while (changed);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        deleteBuffers();
//System.out.println("Done!");
    }
933100
private static Tree traverse(Tree parent, List<Tree> kids, Tree node) {
        for (Tree kid : kids) {
            if (kid == node) {
                return parent;
            }

            Tree ret = node.parent(kid);
            if (ret != null) {
                return ret;
            }
        }
        return null;
    }
738625
function(tree, n, m) {
    return tree[n].fc < tree[m].fc ||
      (tree[n].fc == tree[m].fc && zip_depth[n] <= zip_depth[m]);
}
429893
function depthFirst(node, parent) {
  var results = [];
  if (node && (typeof node === 'object')) {

    // valid node so push it to the list and set new parent
    //  don't overwrite parent if one was not given
    if ('type' in node) {
      if (parent !== undefined) {
        node.parent = parent;
      }
      parent = node;
      results.push(node);
    }

    // recurse object members using nested function call
    for (var key in node) {
      if (WHITE_LIST.test(key)) {
        var value = node[key];
        if (value && (typeof value === 'object')) {
          results.push.apply(results, depthFirst(value, parent));
        }
      }
    }
  }
  return results;
}
813781
private void treeShap(R feat, float[] phi,
                        N node, S nodeStat, int unique_depth,
                        PathPointer parent_unique_path,
                        float parent_zero_fraction,
                        float parent_one_fraction, int parent_feature_index,
                        int condition, int condition_feature,
                        float condition_fraction) {

    // stop if we have no getWeight coming down to us
    if (condition_fraction == 0) return;

    // extend the unique path
    PathPointer unique_path = parent_unique_path.move(unique_depth);

    if (condition == 0 || condition_feature != parent_feature_index) {
      extendPath(unique_path, unique_depth, parent_zero_fraction,
              parent_one_fraction, parent_feature_index);
    }
    final int split_index = node.getSplitIndex();

    // leaf node
    if (node.isLeaf()) {
      for (int i = 1; i <= unique_depth; ++i) {
        final float w = unwoundPathSum(unique_path, unique_depth, i);
        final PathElement el = unique_path.get(i);
        phi[el.feature_index] += w * (el.one_fraction - el.zero_fraction)
                * node.getLeafValue() * condition_fraction;
      }

      // internal node
    } else {
      // find which branch is "hot" (meaning x would follow it)
      final int hot_index = node.next(feat);
      final int cold_index = hot_index == node.getLeftChildIndex() ? node.getRightChildIndex() : node.getLeftChildIndex();
      final float w = nodeStat.getWeight();
      final float hot_zero_fraction = stats[hot_index].getWeight() / w;
      final float cold_zero_fraction = stats[cold_index].getWeight() / w;
      float incoming_zero_fraction = 1;
      float incoming_one_fraction = 1;

      // see if we have already split on this feature,
      // if so we undo that split so we can redo it for this node
      int path_index = 0;
      for (; path_index <= unique_depth; ++path_index) {
        if (unique_path.get(path_index).feature_index == split_index)
          break;
      }
      if (path_index != unique_depth + 1) {
        incoming_zero_fraction = unique_path.get(path_index).zero_fraction;
        incoming_one_fraction = unique_path.get(path_index).one_fraction;
        unwindPath(unique_path, unique_depth, path_index);
        unique_depth -= 1;
      }

      // divide up the condition_fraction among the recursive calls
      float hot_condition_fraction = condition_fraction;
      float cold_condition_fraction = condition_fraction;
      if (condition > 0 && split_index == condition_feature) {
        cold_condition_fraction = 0;
        unique_depth -= 1;
      } else if (condition < 0 && split_index == condition_feature) {
        hot_condition_fraction *= hot_zero_fraction;
        cold_condition_fraction *= cold_zero_fraction;
        unique_depth -= 1;
      }

      treeShap(feat, phi, nodes[hot_index], stats[hot_index], unique_depth + 1, unique_path,
              hot_zero_fraction * incoming_zero_fraction, incoming_one_fraction,
              split_index, condition, condition_feature, hot_condition_fraction);

      treeShap(feat, phi, nodes[cold_index], stats[cold_index], unique_depth + 1, unique_path,
              cold_zero_fraction * incoming_zero_fraction, 0,
              split_index, condition, condition_feature, cold_condition_fraction);
    }
  }
819148
def traverse_depth_first_post_order(self, callback):
        
        # a. Reimplement without python lists?..
        # b. Interface will require it to have not internal nodes only?..
        #    (but actually this implementation gives a ~2x gain of performance)
        last_interval = None
        n = len(self.suftab)
        stack = [[0, 0, None, []]]  # <l, i, j, children>
        for i in xrange(1, n):
            lb = i - 1
            while self.lcptab[i] < stack[-1][0]:
                stack[-1][2] = i - 1
                last_interval = stack.pop()
                callback(last_interval)
                lb = last_interval[1]
                if self.lcptab[i] <= stack[-1][0]:
                    stack[-1][3].append(last_interval)
                    last_interval = None
            if self.lcptab[i] > stack[-1][0]:
                if last_interval:
                    stack.append([self.lcptab[i], lb, None, [last_interval]])
                    last_interval = None
                else:
                    stack.append([self.lcptab[i], lb, None, []])
        stack[-1][2] = n - 1
        callback(stack[-1])
957685
def k_depth(d, depth, _counter=1):
        
        if depth == 0:
            yield d[_meta]["_rootname"]
        else:
            if _counter == depth:
                for key in DictTree.k(d):
                    yield key
            else:
                _counter += 1
                for node in DictTree.v(d):
                    for key in DictTree.k_depth(node, depth, _counter):
                        yield key
619855
def _traverse_iter(o, tree_types=(list, tuple)):
    
    SIMPLERANDOM_BITS = 32
    SIMPLERANDOM_MOD = 2**SIMPLERANDOM_BITS
    SIMPLERANDOM_MASK = SIMPLERANDOM_MOD - 1
    if isinstance(o, tree_types) or getattr(o, '__iter__', False):
        for value in o:
            for subvalue in _traverse_iter(value):
                while True:
                    yield subvalue & SIMPLERANDOM_MASK
                    subvalue >>= SIMPLERANDOM_BITS
                    # If value is negative, then it effectively has infinitely extending
                    # '1' bits (modelled as a 2's complement representation). So when
                    # right-shifting it, it will eventually get to -1, and any further
                    # right-shifting will not change it.
                    if subvalue == 0 or subvalue == -1:
                        break
    else:
        yield o
795447
private void preorderTreeDepth(INode root, HashMap<INode, Integer> order, HashMap<INode, Integer> depth) {
        order.clear();
        depth.clear();

        int num = 1;

        Deque<INode> stack = new ArrayDeque<INode>();
        stack.push(root);
        while (!stack.isEmpty()) {
            INode v = stack.pop();

            order.put(v, num++);
            if (!v.hasParent()) {
                depth.put(v, 0);
            } else {
                depth.put(v, depth.get(v.getParent()) + 1);
            }

            for (int i = v.getChildCount() - 1; i >= 0; i--) {
                stack.push(v.getChildAt(i));
            }
        }
    }
442192
function(array) {
    var firstNode = array.length - 2;
    var nextNode = array.length - 1;
    var currentDepth, availableNodes, lastNode, i;

    for (currentDepth = 1, availableNodes = 2;
         availableNodes > 0;
         currentDepth++) {
      lastNode = firstNode;
      firstNode = first (array, lastNode - 1, 0);

      for (i = availableNodes - (lastNode - firstNode); i > 0; i--) {
        array[nextNode--] = currentDepth;
      }

      availableNodes = (lastNode - firstNode) << 1;
    }
  }
905629
private LinkedList<T> computeRecursiveTraversal(T node, NodePath<T> nodePath) {
    try {


      LinkedList<T> imports = new LinkedList<>();
      Set<T> alreadyIncludedImports = new HashSet<>();

      for (T neighbor : this.traversalFunction.apply(node)) {
        nodePath.appendNode(neighbor);
        addSubtraversal(neighbor, imports, alreadyIncludedImports, nodePath);
        nodePath.popTail();
      }

      return imports;
    } catch (ExecutionException ee) {
      throw new RuntimeException(ee);
    }
  }