Skip to content

Instantly share code, notes, and snippets.

@ObsidianCat
Created May 30, 2020 10:26
Show Gist options
  • Save ObsidianCat/5db29bb5d05fd27379c21cf26af8faa6 to your computer and use it in GitHub Desktop.
Save ObsidianCat/5db29bb5d05fd27379c21cf26af8faa6 to your computer and use it in GitHub Desktop.
Building and traversing of binary tree
// Node definition
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
// Assemle a tree
const left = new TreeNode(2)
const right = new TreeNode(2)
const rightRight = new TreeNode(3)
const root = new TreeNode(1)
right.right = rightRight
root.left = left
root.right = right
// Traverse
// node -> left -> right
function preOrder(root){
if(root == null){
return
}
console.log(root.val)
preOrder(root.left)
preOrder(root.right)
}
// left -> node -> right
function inOrder(root){
if(root == null){
return
}
preOrder(root.left)
console.log(root.val)
preOrder(root.right)
}
// left -> right -> node
function postOrder(root){
if(root == null){
return
}
preOrder(root.left)
preOrder(root.right)
console.log(root.val)
}
preOrder(root)
inOrder(root)
postOrder(root)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment