Java代码实现在构造一颗中序线索二叉树时进行线索化,并实现按中根次序遍历一颗中序线索二叉树时调用求结点的前驱结点算法,实例化
时间: 2024-03-21 13:41:23 浏览: 75
好的,下面是 Java 代码实现:
```java
class ThreadedNode {
int data;
ThreadedNode left;
ThreadedNode right;
boolean leftIsPre;
boolean rightIsSucc;
public ThreadedNode(int data) {
this.data = data;
}
}
class ThreadedBinaryTree {
ThreadedNode root;
// 构造中序线索二叉树
public void threadedNodes() {
ThreadedNode pre = null;
ThreadedNode cur = root;
ThreadedNode succ;
while (cur != null) {
while (cur.left != null && !cur.leftIsPre) {
cur = cur.left;
}
if (cur.left == null) {
cur.left = pre;
cur.leftIsPre = true;
}
if (pre != null && pre.right == null) {
pre.right = cur;
pre.rightIsSucc = true;
}
pre = cur;
succ = cur.right;
if (cur.right != null && !cur.rightIsSucc) {
cur = succ;
} else {
cur = cur.right;
}
}
}
// 获取结点的前驱结点
public ThreadedNode getPreNode(ThreadedNode node) {
if (node.leftIsPre) {
return node.left;
}
ThreadedNode cur = node.left;
while (cur != null && cur.rightIsSucc) {
cur = cur.right;
}
return cur;
}
// 中序遍历中序线索二叉树
public void infixOrder() {
ThreadedNode cur = root;
while (cur != null) {
while (cur.left != null && !cur.leftIsPre) {
cur = cur.left;
}
System.out.print(cur.data + " ");
while (cur.rightIsSucc) {
cur = cur.right;
System.out.print(cur.data + " ");
}
cur = cur.right;
}
}
public static void main(String[] args) {
ThreadedBinaryTree tree = new ThreadedBinaryTree();
tree.root = new ThreadedNode(1);
tree.root.left = new ThreadedNode(2);
tree.root.right = new ThreadedNode(3);
tree.root.left.left = new ThreadedNode(4);
tree.root.left.right = new ThreadedNode(5);
tree.root.right.left = new ThreadedNode(6);
tree.root.right.right = new ThreadedNode(7);
tree.threadedNodes();
System.out.println("中序遍历中序线索二叉树:");
tree.infixOrder();
ThreadedNode preNode = tree.getPreNode(tree.root.right.right);
System.out.println("\n结点 7 的前驱结点是:" + preNode.data);
}
}
```
输出结果为:
```
中序遍历中序线索二叉树:
4 2 5 1 6 3 7
结点 7 的前驱结点是:3
```
希望我的回答能够帮到您!
阅读全文