package DataStructure;
public class ThreadedBinaryTreeDemo {
public static void main(String[] args) {
Node n3=new Node(8);
Node n4=new Node(10);
Node n5=new Node(14);
Node n1=new Node(3,n3,n4);
Node n2=new Node(6);
n2.left=n5;
Node root=new Node(1,n1,n2);
BinaryTree tree=new BinaryTree();
tree.setRoot(root);
tree.threadedNodes();
//对二叉树进行线索化
//todo 注意:即使是线索化之后,也不是所有的指针都得到了利用,有一些节点没有前驱或没有后继节点
System.out.println(n5);
System.out.println(n5.left);
System.out.println(n5.right);
//tree.infixOrder(root);
}
}
class Node {
public int val;
public Node left;
public Node right;
//todo leftType==0 左子树 1 前驱节点
public int leftType;
public int rightType;
public Node() {
}
public Node(int val) {
this.val = val;
}
public Node(int val, Node left, Node right) {
this.val = val;
this.left = left;
this.right = right;
}
public String toString(){
return "val="+val+" leftType="+leftType+" rightType="+rightType;
}
}
//todo 定义二叉树
class BinaryTree {
private Node root;
public Node pre=null;//指向前驱节点
public Node post=null;
public void setRoot(Node root) {
this.root = root;
}
public void infixOrder(Node node){
if(node==null) return ;
if(node.left!=null) infixOrder(node.left);
System.out.println(node);
if(node.right!=null) infixOrder(node.right);
}
//进行重载 使代码简洁
public void threadedNodes(){
this.threadedNodes(root);
}
//中序线索化二叉树
public void threadedNodes(Node node) {
if (node == null) return;
//左子树
if (node!=null && node.left != null) threadedNodes(node.left);
//父节点
if (node!=null && node.leftType == 0 && node.left==null){
//指向前驱节点
node.left=pre;
node.leftType=1;
}
if(pre!=null && pre.rightType==0 && pre.right==null){
//指向后继结点
//让前驱节点的右指针指向当前节点
// todo 前驱节点和后继结点是一对相对的概念
pre.right=node;
pre.rightType=1;
}
pre=node;
//右子树
if (node.right != null) threadedNodes(node.right);
}
}
尚硅谷Java数据结构--线索化二叉树
于 2024-03-05 11:45:11 首次发布