二叉树遍历

二叉树遍历

(前序、中序、后序、层次遍历、广度优先=层次、深度优先=前序)
四种主要的遍历思想为:
前序遍历:根结点 —> 左子树 —> 右子树
中序遍历:左子树—> 根结点 —> 右子树
后序遍历:左子树 —> 右子树 —> 根结点
层次遍历:只需按层次遍历即可

例如,求下面二叉树的各种遍历
在这里插入图片描述
前序遍历: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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

松鼠喵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值