Last active
March 21, 2016 08:47
-
-
Save yanmhlv/bbe2137f125caf594c44 to your computer and use it in GitHub Desktop.
This file contains 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
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) | |
}) |
Author
yanmhlv
commented
Mar 21, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment