binary tree
What is a binary tree?
Each node in the tree can only have at most two child nodes. In JavaScript, Object is generally used to simulate a binary tree.
common operation
- preorder traversal
- Inorder traversal
- post order traversal
preorder traversal
root or so.
Mantra:
- visit the root node
- Preorder traversal of the left subtree of the root node
- Preorder traversal of the right subtree of the root node
Implemented recursively
function preorder(root) {
if (!root) return
console.log(root.val)
preorder(root.left)
preorder(root.right)
}
Implemented iteratively
function preorder(root) {
if (!root) return
const stack = [root]
while (stack.length) {
const n = stack.pop()
console.log(n)
if (n.right) stack.push(n.right)
if (n.left) stack.push(n.left)
}
}
Inorder traversal
Left and right.
Mantra:
- Inorder traversal of the left subtree of the root node
- visit the root node
- Inorder traversal of the right subtree of the root node
Implemented recursively
function inorder(root) {
if (!root) return
inorder(root.left)
console.log(root.val)
inorder(root.right)
}
Implemented iteratively
function inorder(root) {
if (!root) return
const stack = [root]
while (stack.length) {
const n = stack.pop()
console.log(n)
if (n.right) stack.push(n.right)
if (n.left) stack.push(n.left)
}
}
post order traversal
left and right roots.
Mantra:
- Post-order traversal of the left subtree of the root node
- Post-order traversal of the right subtree of the root node
- visit the root node
Implemented recursively
function postorder(root) {
if (!root) return
postorder(root.left)
postorder(root.right)
console.log(root.val)
}
Implemented iteratively
function postorder(root) {
if (!root) return
const outputStack = []
const stack = [root]
while (stack.length) {
const n = stack.pop()
outputStack.push(n)
if (n.left) stack.push(n.left)
if (n.right) stack.push(n.right)
}
while (outputStack.length) {
const n = outputStack.pop()
console.log(n.val)
}
}
Original Link: Vegetable Garden Front End