Skip to content

Instantly share code, notes, and snippets.

@bor0
Created February 14, 2018 10:13
Show Gist options
  • Select an option

  • Save bor0/faff2f5232a933560dc9ac373730f6b5 to your computer and use it in GitHub Desktop.

Select an option

Save bor0/faff2f5232a933560dc9ac373730f6b5 to your computer and use it in GitHub Desktop.
// based off of https://github.com/bor0/misc/blob/master/2017/tree.js
// example: https://github.com/bor0/misc/blob/master/2017/tree_test.js
var tree = {
v: 1,
l: {
v: 2,
l: {
v: 3,
l: { v: 4 },
r: { v: 5 },
},
r: { v: 6 },
},
r: {
v: 7,
l: {
v: 8,
l: { v: 9 },
r: { v: 10 },
},
r: { v: 11 },
}
};
let flat_tree = function(tree) {
let S = [tree], l = [];
while (S.length) {
let v = S.pop();
l.push(v.v);
if (v.r) S.push(v.r);
if (v.l) S.push(v.l);
}
return l;
};
console.log(flat_tree(tree));
@bor0

bor0 commented Feb 14, 2018

Copy link
Copy Markdown
Author

More generalized version:

let fold_tree = function(tree, cb) {
	let S = [tree];
	var l;

	while (S.length) {
		let v = S.pop();

		l = cb(v, S, l);

		if (v.r) S.push(v.r);
		if (v.l) S.push(v.l);
	}

	return l;
};

Usage example for callback:

let flat_tree = function(node, stack, accumulator) {
	accumulator = accumulator || [];
	accumulator.push(node.v);
	return accumulator;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment