tiktok challenge

mail@pastecode.io avatar
unknown
javascript
2 years ago
660 B
3
Indexable
Never
let mainNode = {
	value: 2,
	left: {
		value: 7,
		left: {
			value: 2
		},
		right: {
			value: 6,
			left: {
				value: 5
			},
			right: {
				value: 11
			}
		}
	},
	right: {
		value: 5,
		right: {
			value: 9,
			left: {
				value: 4
			}
		}
	}
}

let arr = [];
let lowestPos = 0;
let highestPos = 0;

function sortThing(node, pos) {
	if (!arr[pos]) {
		arr[pos] = [node.value];
	}
	else arr[pos].push(node.value);
	
	if (node.right) {
		lowestPos--;
		sortThing(node.right, pos-1);
	}
	
	if (node.left) {
		highestPos++;
		sortThing(node.left, pos+1);
	}
}

sortThing(mainNode, 0);

for (let i = lowestPos; i < highestPos; i++) {
	console.log(arr[i]);
}