Java代码实现在构造一颗中序线索二叉树时进行线索化,并调用求结点的前驱结点算法,按中根次序遍历一颗中序线索二叉树,输出运行结果
时间: 2024-03-17 08:40:01 浏览: 60
以下是 Java 代码实现中序线索化二叉树,并输出中序遍历结果及结点的前驱结点的过程:
```java
// 定义线索二叉树结点
class ThreadedNode {
int val;
ThreadedNode left;
ThreadedNode right;
boolean isLeftThreaded;
boolean isRightThreaded;
public ThreadedNode(int val) {
this.val = val;
this.isLeftThreaded = false;
this.isRightThreaded = false;
}
}
// 构造中序线索二叉树
public static ThreadedNode buildThreadedTree(int[] arr) {
if (arr == null || arr.length == 0) {
return null;
}
ThreadedNode root = new ThreadedNode(arr[0]);
ThreadedNode pre = root;
for (int i = 1; i < arr.length; i++) {
ThreadedNode node = new ThreadedNode(arr[i]);
if (node.val < pre.val) {
node.left = pre.left;
pre.left = node;
node.isLeftThreaded = true;
node.right = pre;
} else {
pre.right = node;
node.left = pre;
node.isRightThreaded = true;
node.right = pre.right;
}
pre = node;
}
return root;
}
// 求结点的前驱结点
public static ThreadedNode getPredecessor(ThreadedNode node) {
if (node == null) {
return null;
}
if (node.isLeftThreaded) {
return node.left;
}
if (node.left != null) {
ThreadedNode temp = node.left;
while (!temp.isRightThreaded) {
temp = temp.right;
}
return temp;
}
return null;
}
// 中序遍历线索二叉树
public static void inorderTraversal(ThreadedNode root) {
if (root == null) {
return;
}
ThreadedNode p = root;
while (p.isLeftThreaded) {
p = p.left;
}
while (p != null) {
System.out.print(p.val + " ");
p = getSuccessor(p);
}
}
// 调用函数构造线索二叉树,并输出中序遍历结果及结点的前驱结点
public static void main(String[] args) {
int[] arr = {5, 3, 7, 2, 4, 6, 8};
ThreadedNode root = buildThreadedTree(arr);
inorderTraversal(root); // 输出:2 3 4 5 6 7 8
System.out.println();
System.out.println(getPredecessor(root.right.right).val); // 输出:8
}
```
阅读全文