Tree traversal function that generates nodes. For each subtree, the 
    deepest node is evaluated first. Then, the next-deepest nodes are 
    evaluated until all the nodes in the subtree are generated.
519042
def traversal(root):
    ''''''
    stack = [root]
    while len(stack) > 0:
        node = stack.pop()
        if hasattr(node,'children'):
            if node.children == set():
                try:
                    stack[-1].children.remove(node)
                except:
                    pass
                yield (node,stack)
            else:
                childnode = node.children.pop()
                stack += [node,childnode]
        else: 
            children = [x for x in ast.iter_child_nodes(node)]
            node.children = set(children)
            stack.append(node)
129305
def nest *tree_keys, &_block
      tree_keys = tree_keys[0] if tree_keys[0].is_a? Array

      each_row.each_with_object({}) do |row, current|
        # Create tree
        *keys, last = tree_keys
        current = keys.inject(current) { |c, f| c[row[f]] ||= {} }
        name = row[last]

        if block_given?
          current[name] = yield(row, current, name)
        else
          current[name] ||= []
          current[name].push(row.to_h.delete_if { |key,_value| tree_keys.include? key })
        end
      end
    end
403275
public static <T> Iterable<T> depthFirst(TreeDef<T> treeDef, T node) {
		return () -> new Iterator<T>() {
			Deque<T> queue = new ArrayDeque<>(Arrays.asList(node));

			@Override
			public boolean hasNext() {
				return !queue.isEmpty();
			}

			@Override
			public T next() {
				if (queue.isEmpty()) {
					throw new NoSuchElementException();
				}
				T next = queue.removeLast();
				List<T> children = treeDef.childrenOf(next);
				ListIterator<T> iterator = children.listIterator(children.size());
				while (iterator.hasPrevious()) {
					queue.addLast(iterator.previous());
				}
				return next;
			}
		};
	}
596456
function traverseChildren(tw, type) {
  var child, node, parent, result, sibling;
  node = tw._currentNode[mapChild[type]];
  while (node !== null) {
    result = tw._internalFilter(node);
    if (result === NodeFilter.FILTER_ACCEPT) {
      tw._currentNode = node;
      return node;
    }
    if (result === NodeFilter.FILTER_SKIP) {
      child = node[mapChild[type]];
      if (child !== null) {
        node = child;
        continue;
      }
    }
    while (node !== null) {
      sibling = node[mapSibling[type]];
      if (sibling !== null) {
        node = sibling;
        break;
      }
      parent = node.parentNode;
      if (parent === null || parent === tw.root || parent === tw._currentNode) {
        return null;
      } else {
        node = parent;
      }
    }
  }
  return null;
}
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])
1137645
function() {
			if (!this.children.length)
				return null;
				
			var deepestChild = this;
			while (deepestChild.children.length) {
				deepestChild = deepestChild.children[deepestChild.children.length - 1];
			}
			
			return deepestChild;
		}
108381
function traverse(node, {enter = () => {}, leave = () => {}}, path = []) {
    switch (node.type) {
        // regular non-leaf nodes
        case 'Apply':
            enter(node, path)
            node.args.forEach((arg, index) =>
                traverse(arg, {enter, leave}, [...path, 'args', index]))
            leave(node, path)
            break

        // leaf nodes
        case 'Identifier':
        case 'Number':
        case 'Ellipsis':
            enter(node, path)
            leave(node, path)
            break

        // irregular non-leaf nodes
        case 'Parentheses':
            enter(node, path)
            traverse(node.body, {enter, leave}, [...path, 'body'])
            leave(node, path)
            break

        case 'List':
        case 'Sequence':
            enter(node, path)
            node.items.forEach((item, index) =>
                traverse(item, {enter, leave}, [...path, 'items', index]))
            leave(node, path)
            break

        case 'System':
            enter(node, path)
            node.relations.forEach((rel, index) =>
                traverse(rel, {enter, leave}, [...path, 'relations', index]))
            leave(node, path)
            break

        case 'Placeholder':
            // TODO(kevinb) handle children of the placeholder
            // e.g. we there might #a_0 could match x_0, y_0, z_0, etc.
            enter(node, path)
            leave(node, path)
            break

        default:
            throw new Error(`unrecognized node: ${node.type}`)
    }
}
169095
function TreeIterator(tree) {

    // the tree, current slot index, and previous and next pointers are private attributes
    // so methods that use them are defined in the constructor
    var currentSlot = 0;  // the slot before the first item
    var previous = undefined;
    var next = minimum(tree.root);

    this.toStart = function() {
        currentSlot = 0;  // the slot before the first item
        previous = undefined;
        next = minimum(tree.root);
    };

    this.toSlot = function(slot) {
        currentSlot = slot;
        previous = tree.node(slot - 1);  // javascript index of item before the slot
        next = successor(previous);
    };

    this.toEnd = function() {
        currentSlot = tree.size;  // the slot after the last item
        previous = maximum(tree.root);
        next = undefined;
    };

    this.hasPrevious = function() {
        return currentSlot > 0;
    };

    this.hasNext = function() {
        return currentSlot < tree.size;
    };

    this.getPrevious = function() {
        if (!this.hasPrevious()) return;
        const value = previous.value;
        next = previous;
        previous = predecessor(next);
        currentSlot--;
        return value;
    };

    this.getNext = function() {
        if (!this.hasNext()) return;
        const value = next.value;
        previous = next;
        next = successor(previous);
        currentSlot++;
        return value;
    };

    return this;
}
1048187
def v_depth(d, depth):
        
        if depth == 0:
            yield d
        else:
            for node in DictTree.v(d):
                for node1 in DictTree.v_depth(node, depth-1):
                    yield node1
591420
public function depthFirst($tree = [], \Closure $callback = null)
    {
        if (!$tree) {
            $tree = $this->tree;
        }
        foreach ($tree as $node) {
            if ($callback) {
                call_user_func_array($callback, ['node' => $node]);
            }
            $children = $node['children'];
            if ($children) {
                $this->depthFirst($children, $callback);
            }
        }
    }
491687
function recursive (node, depth, index) {
    let hashLeft
    let hashRight
    let summingBuffer

    // case with single node in tree
    if (depth === 0 && node.val !== undefined) {
      return getHash(node.val, depth, index * 2)
    }

    if (node.left === undefined) {
      throw new Error('Left node is missed.')
    }
    if (typeof node.left === 'string') {
      if (!validateHexadecimal(node.left)) {
        throw new TypeError('Tree element of wrong type is passed. Hexadecimal expected.')
      }
      hashLeft = node.left
    } else {
      if (!isObject(node.left)) {
        throw new TypeError('Invalid type of left node.')
      }
      if (node.left.val !== undefined) {
        hashLeft = getHash(node.left.val, depth, index * 2)
      } else {
        hashLeft = recursive(node.left, depth + 1, index * 2)
      }
    }

    if (depth === 0) {
      rootBranch = 'right'
    }

    if (node.right !== undefined) {
      if (typeof node.right === 'string') {
        if (!validateHexadecimal(node.right)) {
          throw new TypeError('Tree element of wrong type is passed. Hexadecimal expected.')
        }
        hashRight = node.right
      } else {
        if (!isObject(node.right)) {
          throw new TypeError('Invalid type of right node.')
        }

        if (node.right.val !== undefined) {
          hashRight = getHash(node.right.val, depth, index * 2 + 1)
        } else {
          hashRight = recursive(node.right, depth + 1, index * 2 + 1)
        }
      }

      summingBuffer = new Uint8Array(64)
      summingBuffer.set(hexadecimalToUint8Array(hashLeft))
      summingBuffer.set(hexadecimalToUint8Array(hashRight), 32)
      return hash(summingBuffer)
    }

    if (depth === 0 || rootBranch === 'left') {
      throw new Error('Right leaf is missed in left branch of tree.')
    }
    summingBuffer = hexadecimalToUint8Array(hashLeft)
    return hash(summingBuffer)
  }
1036016
function(node, callback, depth) {
			if (this.isSkipped(node)) {
				return;
			}

			var childNode,
				childNodes = node && node.childNodes || [];

			depth = (depth || 1);

			for (var n = 0, len = childNodes.length; n < len; n++) {
				childNode = childNodes[n];

				// callback can return false to stop recursive
				if (callback(childNode, depth) !== false) {
					this.walk(childNode, callback, depth + 1);
				}
			}
		}
637774
private static <ID, DATA> void generateSubNode(final TreeSource<ID, DATA> source, final DefaultTree<ID, DATA> node) {
		List<ID> items = source.listChildrenId(node.getId());
		if (items == null || items.isEmpty()) {
			return;
		}
		for (ID id : items) {
			DATA item = source.getItem(id);
			node.appendChildNode(id, item);
		}
		for (DefaultTree<ID, DATA> subNode : new ArrayList<>(node.getChildNodes().values())) {
			generateSubNode(source, subNode);
		}
	}
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)
799987
def walk_tree(self, top=None):
        
        if top is None:
            top = self.rootgrp

        values = top.groups.values()
        yield values
        for value in top.groups.values():
            for children in self.walk_tree(value):
                yield children
5361
function depthFirstSearch(obj, handler) {
  var childrenKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'children';
  var reverse = arguments[3];

  var rootChildren = hp.isArray(obj) ? obj : [obj];
  //
  var StopException = function StopException() {};
  var func = function func(children, parent) {
    if (reverse) {
      children = children.slice();
      children.reverse();
    }
    var len = children.length;
    for (var i = 0; i < len; i++) {
      var item = children[i];
      var r = handler(item, i, parent);
      if (r === false) {
        // stop
        throw new StopException();
      } else if (r === 'skip children') {
        continue;
      } else if (r === 'skip siblings') {
        break;
      }
      if (item[childrenKey] != null) {
        func(item[childrenKey], item);
      }
    }
  };
  try {
    func(rootChildren);
  } catch (e) {
    if (e instanceof StopException) {
      // stop
    } else {
      throw e;
    }
  }
}
561240
def deep_nodes(self, allnodes=None):
        
        allnodes = (allnodes or [])
        for (node, node_) in ((node, node_) for (node, node_) in\
            self.iteritems() if not node in allnodes):
            allnodes.append(node)
            node_.deep_nodes(allnodes)
        return allnodes