二叉查询树三种遍历的非递归写法

本文详细介绍了二叉查找树的三种非递归遍历方式:前序遍历、中序遍历和后序遍历。通过使用栈数据结构,实现了不依赖递归的遍历算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里写出三种儿叉查询树遍历的非递归写法,非常有意思。

preorder:先打印root,再left,最后right。

public static void BSTPreorderTraverse(Node node) { if (node == null) { return; } Stack<Node> s = new Stack<Node>(); s.push(node); while (!s.empty()) { node = s.pop(); System.out.println(node.toString()); if (node.rightChild != null) {s.push(node.rightChild);} if (node.leftChild != null) {s.push(node.leftChild);} } }

Inorder: 先打印left,再root,最后right.

public static void BSTInorderTraverse(Node node) { Stack<Node> s = new Stack<Node>(); while (!s.empty() || node != null) { if (node != null) { s.push(node); node = node.leftChild; } else { node = s.pop(); System.out.println(node.toString()); node = node.rightChild; } } }

Preorder: 先打印left,再right,最后root.

class Node {

public static void BSTPostorderTraverse(Node node) { if (node == null) { return; } Stack<Node> s = new Stack<Node>(); Node cur = node; while (true) { if (cur != null) { if (cur.rightChild != null) { s.push(cur.rightChild); } s.push(cur); cur = cur.leftChild; continue; } if (s.empty()) { return; } cur = s.pop(); if (cur.rightChild != null && !s.empty() && cur.rightChild == s.peek()) { s.pop(); s.push(cur); cur = cur.rightChild; } else { System.out.println(cur.toString()); cur = null; } } }

Node leftChild = null; Node rightChild = null; String name; Node(String name) { this.name = name; } @Override public String toString() { return name; } }

参考:http://en.wikipedia.org/wiki/Inorder

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值