java代码实现线索化构造一棵中序线索二叉树,并在其中实现调用求结点的前驱结点算法,按中根次序遍历一颗中序线索二叉树,并实例化该类
时间: 2024-03-18 18:38:34 浏览: 117
好的,以下是Java代码实现线索化构造一棵中序线索二叉树,并在其中实现调用求结点的前驱结点算法,按中根次序遍历一颗中序线索二叉树的示例代码:
```java
// 定义线索二叉树结点类
class ThreadedNode {
int val;
ThreadedNode left;
ThreadedNode right;
boolean isThreaded;
public ThreadedNode(int val) {
this.val = val;
}
}
// 定义中序线索二叉树类
class ThreadedBinaryTree {
private ThreadedNode root;
private ThreadedNode prev;
// 构造中序线索二叉树
public void buildThreadedTree(ThreadedNode node) {
if (node == null) {
return;
}
buildThreadedTree(node.left);
if (node.left == null) {
node.left = prev;
node.isThreaded = true;
}
if (prev != null && prev.right == null) {
prev.right = node;
prev.isThreaded = true;
}
prev = node;
buildThreadedTree(node.right);
}
// 求结点的前驱结点算法
public ThreadedNode getPrevNode(ThreadedNode node) {
if (node == null) {
return null;
}
if (node.left != null) {
ThreadedNode temp = node.left;
while (temp.right != null && !temp.isThreaded) {
temp = temp.right;
}
return temp;
} else {
return node.isThreaded ? node.left : null;
}
}
// 中根次序遍历中序线索二叉树
public void inOrderTraversal() {
ThreadedNode node = root;
while (node != null) {
while (node.left != null && !node.isThreaded) {
node = node.left;
}
System.out.print(node.val + " ");
if (node.isThreaded) {
node = node.right;
} else {
node = node.right != null ? node.right : node;
}
}
System.out.println();
}
// 实例化中序线索二叉树类
public static void main(String[] args) {
ThreadedBinaryTree tbt = new ThreadedBinaryTree();
ThreadedNode root = new ThreadedNode(4);
root.left = new ThreadedNode(2);
root.right = new ThreadedNode(6);
root.left.left = new ThreadedNode(1);
root.left.right = new ThreadedNode(3);
root.right.left = new ThreadedNode(5);
root.right.right = new ThreadedNode(7);
tbt.root = root;
tbt.buildThreadedTree(tbt.root);
tbt.inOrderTraversal();
System.out.println(tbt.getPrevNode(root.right.right).val);
}
}
```
该代码实现了线索化构造一棵中序线索二叉树,并在其中实现调用求结点的前驱结点算法,按中根次序遍历一颗中序线索二叉树的功能,可以直接运行测试。
阅读全文