遍历方式
先序遍历:根 → 左 → 右
中序遍历:左 → 根 → 右
后序遍历:左 → 右 → 根
下面我将分别用递归的方法进行代码的讲解:
先构造一棵小树,用小树的例子进行讲解

1.先序遍历:
public void preOrder(TreeNode root) {
if (root == null) return;
System.out.print(root.val + " "); // 根
preOrder(root.left); // 左
preOrder(root.right); // 右
}
过程:
1.调用 preOrder(1)
不为空,打印:
递归左孩子:preOrder(2)
2.调用 preOrder(2)
不为空,打印:2
递归左孩子:preOrder(4)
3.调用 preOrder(4)
不为空,打印:4
递归左孩子:preOrder(null) → 直接返回
递归右孩子:preOrder(null) → 直接返回
函数结束,回到上一层(节点 2)
回到 preOrder(2)
4.左子树走完了,现在递归右孩子:preOrder(null) → 返回
函数结束,回到上一层(节点 1)
回到 preOrder(1)
5.左子树走完了,递归右孩子:preOrder(3)
6.调用 preOrder(3)
不为空,打印:3
左、右都是 null,直接返回
回到节点 1,整个遍历结束
先序结果:1 2 4 3
2.中序遍历:
public void inOrder(TreeNode root) {
if (root == null) return;
inOrder(root.left); // 左
System.out.print(root.val + " "); // 根
inOrder(root.right); // 右
}
过程:
1.inOrder(1)
先递归左:inOrder(2)
2.inOrder(2)
先递归左:inOrder(4)
3.inOrder(4)
递归左:inOrder(null) 返回
打印:4
递归右:inOrder(null) 返回
回到节点 2
4.回到 inOrder(2)
左走完,打印:2
递归右:inOrder(null) 返回
回到节点 1
5.回到 inOrder(1)
左走完,打印:1
6.递归右:inOrder(3)
inOrder(3)
递归左:null
打印:3
递归右:null
结束
中序结果:4 2 1 3
3.后序遍历:
public void postOrder(TreeNode root) {
if (root == null) return;
postOrder(root.left); // 左
postOrder(root.right); // 右
System.out.print(root.val + " "); // 根
}
过程:
1.postOrder(1) → 先走左 postOrder(2)
2.postOrder(2) → 先走左 postOrder(4)
3.postOrder(4)
左:null
右:null
打印:4
返回节点 2
4.回到 postOrder(2)
左走完,走右:null
打印:2
返回节点 1
5.回到 postOrder(1)
左走完,走右 postOrder(3)
6.postOrder(3)
左、右都 null
打印:3
返回节点 1
7.回到 postOrder(1)
左右都走完
打印:1
后序结果:4 2 3 1