树
const tree = {
val: 'a',
children: [
{
val: 'b',
children: [{ val: 'd' }, { val: 'e' }],
},
{
val: 'c',
children: [{ val: 'f' }, { val: 'g' }],
},
],
}

深度优先遍历
function dfs(tree) {
const { val, children } = tree
console.log(val)
children && children.forEach(dfs)
}
广度优先遍历
function bfs(tree) {
const queue = [tree]
while (queue.length) {
const { val, children } = queue.shift()
console.log(val)
children && queue.push(...children)
}
}
二叉树
const tree = {
val: 1,
left: {
val: 2,
left: { val: 4 },
right: { val: 5 },
},
right: {
val: 3,
left: { val: 6 },
right: { val: 7 },
},
}
前序遍历

function preOrder(root) {
if (!root) return
console.log(root.val)
preOrder(root.left)
preOrder(root.right)
}
function preOrder(root) {
if (!root) return
const stack = [root]
while (stack.length) {
const { val, left, right } = stack.pop()
console.log(val)
right && stack.push(right)
left && stack.push(left)
}
}
中序遍历

function inOrder(root) {
if (!root) return
inOrder(root.left)
console.log(root.val)
inOrder(root.right)
}
function inOrder(root) {
if (!root) return
const stack = []
let p = root
while (stack.length || p) {
while (p) {
stack.push(p)
p = p.left
}
const { val, right } = stack.pop()
console.log(val)
p = right
}
}
后序遍历

function postOrder(root) {
if (!root) return
postOrder(root.left)
postOrder(root.right)
console.log(root.val)
}
function postOrder(root) {
if (!root) return
const output = []
const stack = [root]
while (stack.length) {
const { val, left, right } = stack.pop()
output.push(val)
left && stack.push(left)
right && stack.push(right)
}
while (output.length) {
console.log(output.pop())
}
}
leetcode 真题
堆

class MinHeap {
heap = []
insert(val) {
this.heap.push(val)
this.shiftUp(this.heap.length - 1)
}
shiftUp(index) {
if (index === 0) return
const parentIndex = this.getParentIndex(index)
if (this.heap[parentIndex] > this.heap[index]) {
this.swap(parentIndex, index)
this.shiftUp(parentIndex)
}
}
pop() {
this.heap[0] = this.heap.pop()
this.shiftDown(0)
}
shiftDown(index) {
const leftIndex = this.getLeftIndex(index)
const rightIndex = this.getRightIndex(index)
if (this.heap[leftIndex] < this.heap[index]) {
this.swap(index, leftIndex)
this.shiftDown(leftIndex)
}
if (this.heap[rightIndex] < this.heap[index]) {
this.swap(index, rightIndex)
this.shiftDown(rightIndex)
}
}
swap(i1, i2) {
const temp = this.heap[i1]
this.heap[i1] = this.heap[i2]
this.heap[i2] = temp
}
getParentIndex = index => (index - 1) >> 1
getLeftIndex = index => index * 2 + 1
getRightIndex = index => index * 2 + 2
peek = () => this.heap[0]
size = () => this.heap.length
}
测试
const heap = new MinHeap()
heap.insert(3)
heap.insert(2)
heap.insert(1)
heap.insert(8)
heap.insert(9)
heap.insert(4)
heap.insert(5)
heap.insert(6)
heap.pop()
heap.pop()
leetcode