前、中、后序遍历

前序遍历(根、左、右)

  1. preOrder(root){
  2. if(!root) return
  3. XXXXXX(root) // 处理逻辑,比如放入数组
  4. preOrder(root.left)
  5. preOrder(root.right)
  6. }

中序遍历(左、根、右)

  1. midOrder(root){
  2. if(!root) return
  3. midOrder(root.left)
  4. XXXXX(root) // 处理逻辑,比如放入数组
  5. midOrder(root.right)
  6. }

后序遍历(左、右、根)

  1. lastOrder(root){
  2. if(!root) return
  3. lastOrder(root.left)
  4. lastOrder(root.right)
  5. XXXXX(root) // 处理逻辑,比如放入数组
  6. }

层序遍历(BFS 广度优先搜索)

  1. // bfs就不递归了
  2. bfs(root){
  3. let queue = []
  4. queue.push(root)
  5. while(queue.length){
  6. const queLen = queue.length
  7. for(let i = 0;i++;i<queLen){
  8. const node = queue.shift()
  9. XXXXX(node) // 处理逻辑,比如放入数组
  10. if(node.left) queue.push(node.left)
  11. if(node.right) queue.push(node.right)
  12. }
  13. }
  14. }