# 二叉树的先中后序遍历

// 二叉树的遍历主要有三种:
// (1)先(根)序遍历(根左右)
// (2)中(根)序遍历(左根右)
// (3)后(根)序遍历(左右根)
const tree = {
  val: 1,
  left: {
    val: 2,
    left: {
      val: 3,
    },
  },
  right: {
    val: 4,
    left: {
      val: 5,
    },
    right: {
      val: 6,
    },
  },
};

// 先序遍历
function before(tree) {
  function dfs(tree) {
    console.log(tree.val);
    tree.left && dfs(tree.left);
    tree.right && dfs(tree.right);
  }
  dfs(tree);
}

// 中序遍历
function center(tree) {
  function dfs(tree) {
    tree.left && dfs(tree.left);
    console.log(tree.val);
    tree.right && dfs(tree.right);
  }
  dfs(tree);
}

// 后序遍历
function after(tree) {
  function dfs(tree) {
    tree.left && dfs(tree.left);
    tree.right && dfs(tree.right);
    console.log(tree.val);
  }
  dfs(tree);
}

// console.log(before(tree));
// console.log(center(tree));
// console.log(after(tree));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Last Updated: 7/3/2023, 11:54:34 PM