二叉树的遍历

前序遍历

递归:

  1. function preorderTraversal(root) {
  2. if (root === null) {
  3. return
  4. }
  5. console.log(root.val)
  6. inorderTraversal(root.left)
  7. inorderTraversal(root.right)
  8. }

迭代:

  1. function preorderTraversal(root) {
  2. const stack = [root]
  3. while (stack.length > 0) {
  4. const node = stack.pop()
  5. if (node === null) {
  6. continue
  7. }
  8. console.log(node.val)
  9. stack.push(node.right)
  10. stack.push(node.left)
  11. }
  12. }

中序遍历:

递归:

  1. function inorderTraversal(root) {
  2. if (root === null) {
  3. return
  4. }
  5. inorderTraversal(root.left)
  6. console.log(root.val)
  7. inorderTraversal(root.right)
  8. }

迭代:

  1. function inorderTraversal(root) {
  2. const stack = []
  3. while (root || stack.length > 0) {
  4. if (root) {
  5. stack.push(root)
  6. root = root.left
  7. } else {
  8. root = stack.pop()
  9. console.log(root.val)
  10. root = root.right
  11. }
  12. }
  13. }

后序遍历:

递归:

  1. function postorderTraversal(root) {
  2. if (root === null) {
  3. return
  4. }
  5. inorderTraversal(root.left)
  6. inorderTraversal(root.right)
  7. console.log(root.val)
  8. }

迭代:

  1. function postorderTraversal(root) {
  2. const stack = []
  3. let prev = null
  4. while (root || stack.length > 0) {
  5. if (root) {
  6. stack.push(root)
  7. root = root.left
  8. } else {
  9. root = stack.pop()
  10. if (!root.right || root.right === prev) {
  11. console.log(root.val)
  12. prev = root
  13. root = null
  14. } else {
  15. stack.push(root)
  16. root = root.right
  17. }
  18. }
  19. }
  20. }

层序遍历:

  1. function levelOrder(root) {
  2. if (root === null) {
  3. return
  4. }
  5. const queue = [root]
  6. while (queue.length > 0) {
  7. const node = queue.shift()
  8. console.log(node.val)
  9. if (node.left) {
  10. queue.push(node.left)
  11. }
  12. if (node.right) {
  13. queue.push(node.right)
  14. }
  15. }
  16. }

二叉搜索树
完美二叉树
满二叉树
线索二叉树