Skip to content

Instantly share code, notes, and snippets.

@yanmhlv
Last active March 21, 2016 08:47
Show Gist options
  • Save yanmhlv/bbe2137f125caf594c44 to your computer and use it in GitHub Desktop.
Save yanmhlv/bbe2137f125caf594c44 to your computer and use it in GitHub Desktop.
function levelOrder (node, visit) {
'use strict'
let queue = [node]
while (queue.length > 0) {
node = queue.pop()
if (!node) {
continue
}
visit(node)
queue.push(node.left, node.right)
}
}
function preOrder (node, visit) {
'use strict'
if (!node) {
return
}
preOrder(node.left, visit)
preOrder(node.right, visit)
visit(node)
}
function inOrder (node, visit) {
'use strict'
if (!node) {
return
}
inOrder(node.left, visit)
visit(node)
inOrder(node.right, visit)
}
function postOrder (node, visit) {
'use strict'
if (!node) {
return
}
postOrder(node.left, visit)
postOrder(node.right, visit)
visit(node)
}
var node = {
value: 10,
left: {
value: 20,
right: {
value: 30,
left: {
value: 40
},
right: {
value: 50,
}
}
}
}
console.log('# levelOrder #')
levelOrder(node, function (n) {
console.log(n.value)
})
console.log('# postOrder #')
preOrder(node, function (n) {
console.log(n.value)
})
console.log('# inOrder #')
inOrder(node, function (n) {
console.log(n.value)
})
console.log('# postOrder #')
postOrder(node, function (n) {
console.log(n.value)
})
@yanmhlv
Copy link
Author

yanmhlv commented Mar 21, 2016

# levelOrder #
10
20
30
50
40
# postOrder #
40
50
30
20
10
# inOrder #
20
40
30
50
10
# postOrder #
40
50
30
20
10

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