概念

链式存储

1. 先序遍历

2.1 递归解法

解题思路
代码

  1. preorder_recur(node) {
  2. if (!node) {
  3. node = this.root
  4. }
  5. console.log(node.data)
  6. this.preorder_recur(node.left)
  7. this.preorder_recur(node.right)
  8. }

1.2 非递归解法

解题思路
代码

  1. preorder(node) {
  2. if (!node) {
  3. node = this.root
  4. }
  5. let stack = []
  6. let res = []
  7. stack.push(node)
  8. if (node === null) {
  9. return []
  10. }
  11. while (stack.length > 0) {
  12. let node = stack.pop()
  13. res.push(node.val)
  14. if (node.right) {
  15. stack.push(node.right)
  16. }
  17. if (node.left) {
  18. stack.push(node.left)
  19. }
  20. }
  21. return res
  22. }

2. 中序遍历

2.1 递归解法

  1. if (!node) {
  2. node = this.root
  3. }
  4. this.preorder_recur(node.left)
  5. console.log(node.data)
  6. this.preorder_recur(node.right)

2.2 非递归解法

  1. inorder(node) {
  2. if (!node) {
  3. node = this.root
  4. }
  5. let stack = []
  6. let res = []
  7. if (node === null) {
  8. return []
  9. }
  10. while (node !== null || stack.length > 0) {
  11. while (node !== null) {
  12. stack.push(node)
  13. node = node.left
  14. }
  15. node = stack.pop()
  16. res.push(node.data)
  17. node = node.right
  18. }
  19. }

3. 后序遍历

3.1 递归解法

  1. postorder_recur(node) {
  2. if (!node) {
  3. node = this.root
  4. }
  5. this.preorder_recur(node.left)
  6. this.preorder_recur(node.right)
  7. console.log(node.data)
  8. }

3.2 非递归解法

线性存储