This article directly connected with basic tree implementation example, and here you will find some additional methods . All methods did recursively. All of those methods are useful when you want to get a data list, it is a little bit trickier than in linear data structures, but the solution pretty easy.
class Tree {
.... <- methods which you can find in the previous article
static inOrder(root) {
if (root) {
this.inOrder(root.right)
console.log(root.value)
this.inOrder(root.left)
}
}
static postOrder(root) {
if (root) {
this.postOrder(root.left)
this.postOrder(root.right)
console.log(root.value)
}
}
static preOrder(root) {
if (root) {
console.log(root.value)
this.preOrder(root.left)
this.preOrder(root.right)
}
}
}
... <- tree initialization and adding values,
also, you can find in prev article
Tree.preOrder(tree) // 20,10,14,40,25
Tree.postOrder(tree) // 14,10,25,40,20
Tree.inOrder(tree) // 40,25,20,14,10