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();
threadedBinaryTree.threadedList();
}
}
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 threadedList() {
Node node = root;
while(node != null) {
while (node.leftType == 0) {
node = node.left;
}
System.out.print("=>"+node);
while(node.rightType == 1) {
node = node.right;
System.out.print("=>"+node);
}
node = node.right;
}
}
}
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 + "";
}
}
线索化二叉树的遍历
最新推荐文章于 2022-08-27 12:43:03 发布