二叉树遍历
(前序、中序、后序、层次遍历、广度优先=层次、深度优先=前序)
四种主要的遍历思想为:
前序遍历:根结点 —> 左子树 —> 右子树
中序遍历:左子树—> 根结点 —> 右子树
后序遍历:左子树 —> 右子树 —> 根结点
层次遍历:只需按层次遍历即可
例如,求下面二叉树的各种遍历
前序遍历:1 2 4 5 7 8 3 6
中序遍历:4 2 7 5 8 1 3 6
后序遍历:4 7 8 5 2 6 3 1
广度优先遍历,层次遍历:1 2 3 4 5 6 7 8
深度优先遍历,前序遍历:1 2 4 5 7 8 3 6
一、前序,中序,后序 遍历
递归的方式框架:
void traverse(TreeNode root) {
// 前序遍历
// System.out.print(root.getVal() + " ");
traverse(root.left)
// 中序遍历
// System.out.print(root.getVal() + " ");
traverse(root.right)
// 后序遍历
// System.out.print(root.getVal() + " ");
}
非递归的方式框架:
// 中序遍历 (利用栈,先进后出)
public static void traverse_zx(TreeNode root) {
if (root == null) {
System.out.println(" tree is empty .");
}
Stack<TreeNode> stack = new Stack();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
//一直往左压入栈
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
System.out.print(cur.val + " ");
cur = cur.right;
}
}
// 后序遍历
public static void traverse_hx(TreeNode root) {
if (root == null) {
System.out.println(" tree is empty .");
}
Stack<TreeNode> stack = new Stack();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
//一直往左压入栈
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
System.out.print(cur.val + " ");
cur = cur.right;
}
}
四、广度优先遍历,层次遍历
层次遍历的代码比较简单,只需要一个队列即可,先在队列中加入根结点。之后对于任意一个结点来说,在其出队列的时候,访问之。同时如果左孩子和右孩子有不为空的,入队列。代码如下:
public void levelTraverse(TreeNode root) {
if (root == null) {
return;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
System.out.print(node.val+" ");
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
五、深度优先遍历
其实深度遍历其实就是前序遍历,代码如下:
// 中序遍历 (利用栈,先进后出)
public static void traverse_zx(TreeNode root) {
if (root == null) {
System.out.println(" tree is empty .");
}
Stack<TreeNode> stack = new Stack();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
//一直往左压入栈
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
System.out.print(cur.val + " ");
cur = cur.right;
}
}