Last active
July 23, 2024 04:32
-
-
Save gofer/c39ec18e975e6afdcde3d84baf10cbd2 to your computer and use it in GitHub Desktop.
Binary tree traversal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const tree = { | |
value: 'A', | |
left: { | |
value: 'B', | |
left: 'D', | |
right: 'E', | |
}, | |
right: { | |
value: 'C', | |
left: 'F', | |
right: 'G', | |
}, | |
}; | |
function inOrder(tree) { | |
const array = []; | |
if (!tree) { return array; } | |
if (typeof(tree) === 'object' && 'left' in tree) { | |
array.push(inOrder(tree.left)); | |
} | |
if (typeof(tree) !== 'object') { | |
array.push(tree); | |
} else if (typeof(tree) === 'object' && 'value' in tree) { | |
array.push(tree.value); | |
} | |
if (typeof(tree) === 'object' && 'right' in tree) { | |
array.push(inOrder(tree.right)); | |
} | |
return array.flat(); | |
} | |
inOrder(tree); | |
function preOrder(tree) { | |
const array = []; | |
if (!tree) { return array; } | |
if (typeof(tree) !== 'object') { | |
array.push(tree); | |
} else if (typeof(tree) === 'object' && 'value' in tree) { | |
array.push(tree.value); | |
} | |
if (typeof(tree) === 'object' && 'left' in tree) { | |
array.push(preOrder(tree.left)); | |
} | |
if (typeof(tree) === 'object' && 'right' in tree) { | |
array.push(preOrder(tree.right)); | |
} | |
return array.flat(); | |
} | |
preOrder(tree); | |
function postOrder(tree) { | |
const array = []; | |
if (!tree) { return array; } | |
if (typeof(tree) === 'object' && 'left' in tree) { | |
array.push(postOrder(tree.left)); | |
} | |
if (typeof(tree) === 'object' && 'right' in tree) { | |
array.push(postOrder(tree.right)); | |
} | |
if (typeof(tree) !== 'object') { | |
array.push(tree); | |
} else if (typeof(tree) === 'object' && 'value' in tree) { | |
array.push(tree.value); | |
} | |
return array.flat(); | |
} | |
postOrder(tree); | |
function levelOrder(tree) { | |
const array = []; | |
if (!tree) { return array; } | |
const queue = []; | |
queue.push(tree); | |
while (queue.length > 0) { | |
const item = queue.shift(); | |
if (typeof(item) !== 'object') { | |
array.push(item); | |
} else if (typeof(item) === 'object' && 'value' in item) { | |
array.push(item.value); | |
} | |
if (typeof(item) === 'object' && 'left' in item) { | |
queue.push(item.left); | |
} | |
if (typeof(item) === 'object' && 'right' in item) { | |
queue.push(item.right); | |
} | |
} | |
return array; | |
} | |
levelOrder(tree); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Given tree has the following structure.
And, these functions return the following values.