Created
May 30, 2020 10:26
-
-
Save ObsidianCat/5db29bb5d05fd27379c21cf26af8faa6 to your computer and use it in GitHub Desktop.
Building and traversing of binary tree
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
// 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