public class ThreadedBinaryTreeDemo {
public static void main(String[] args) {
ThreadedBinaryTree threadedBinaryTree = new ThreadedBinaryTree();
Node one = new Node(1);
Node three = new Node(3);
Node six = new Node(6);
Node eight = new Node(8);
Node ten = new Node(10);
Node fourteen = new Node(14);
Node fifteen = new Node(15);
Node two = new Node(2);
/*
创建二叉树:
1
/ \
3 6
/ \ / \
8 10 14 15
/
2
*/
threadedBinaryTree.setRoot(one);
one.left = three;
one.right = six;
three.left = eight;
three.right = ten;
six.left = fourteen;
six.right = fifteen;
fourteen.left = two;
threadedBinaryTree.threadedBinaryTree();
System.out.println("线索化二叉树结果:");
threadedBinaryTree.infixOrder();
}
}
class ThreadedBinaryTree {
public Node root;
public Node pre = null;
public void setRoot(Node root) {
this.root = root;
}
public void threadedBinaryTree() {
threadedBinaryTree(this.root);
}
public void threadedBinaryTree(Node current) {
if (current == null) {
return;
}
//线索化当前节点的左子节点
threadedBinaryTree(current.left);
//线索化当前节点
if (current.left == null) {
current.left = pre;
current.leftType = 1;
}
if (pre != null && pre.right == null) {
pre.right = current;
pre.rightType = 1;
}
pre = current;
//线索化当前节点的右子节点
threadedBinaryTree(current.right);
}
public void infixOrder() {
if (root != null) {
root.infixOrder();
} else {
System.out.println("二叉树为空~");
}
}
}
class Node {
public int num;
public Node left;
public Node right;
public int leftType;
public int rightType;
public Node(int num) {
this.num = num;
}
@Override
public String toString() {
return num + "";
}
public void infixOrder() {
if(this.left != null) {
if (this.leftType == 0) {
this.left.infixOrder();
} else {
System.out.print(this.left.num);
}
}
if(!(this.leftType == 0 && this.rightType == 0)){
System.out.print("<=" + num + "=>");
}
if(this.right != null){
if (this.rightType == 0) {
this.right.infixOrder();
} else {
System.out.println(this.right.num);
}
}
}
}
线索化二叉树
最新推荐文章于 2024-02-17 18:05:59 发布