线索二叉树
1、问题的提出
2、线索二叉树的概念
- n个节点的二叉链表中包含有n+1个空指针域【2n -(n-1) = n+1】{如上图,n为6,空指针域为 7},利用二叉链表中的空指针域,存放指向该节点在(前中后序遍历)下的前驱和后继节点的指针。
- 这种加上线索的二叉链表称为线索链表,相应的二叉树称为线索二叉树。线索二叉树可分为前序线索二叉树,中序线索二叉树和后序线索二叉树。
- 一个节点的前一个节点,称为前驱节点,后一个节点称为后继节点
3、线索二叉树的分析
4、线索二叉树代码分析
public class ThreadedBinaryTreeDemo {
public static void main(String[] args) {
Node root = new Node(1, "node1");
Node node2 = new Node(3, "node1");
Node node3 = new Node(6, "node1");
Node node4 = new Node(8, "node1");
Node node5 = new Node(10, "node1");
Node node6 = new Node(14, "node1");
root.setLeft(node2);
root.setRight(node3);
node2.setLeft(node4);
node2.setRight(node5);
node3.setLeft(node6);
ThreadedBinaryTree threadedBinaryTree = new ThreadedBinaryTree(root);
threadedBinaryTree.threadedNodes();
// 拿着编号no为10的来测试,看一下10的左指针是不是3,右指针为1
Node left = node5.getLeft();
Node right = node5.getRight();
System.out.println("left = " + left);
System.out.println("right = " + right);
}
}
class ThreadedBinaryTree {
private Node root;
// 保留当前节点的前驱节点
private Node pre = null;
public ThreadedBinaryTree(Node root) {
this.root = root;
}
public void threadedNodes(){
this.threadedNodes(root);
}
public void threadedNodes(Node node) {
if (node == null) {
return;
}
// 先线索化左边
threadedNodes(node.getLeft());
// 处理前驱节点
if (node.getLeft() == null) {
node.setLeft(pre);
node.setLeftType(1);
}
// 处理后继节点
if (pre != null && pre.getRight() == null) {
pre.setRight(node);
pre.setRightType(1);
}
pre = node;
threadedNodes(node.getRight());
}
}
class Node {
private int no;
private String name;
private Node left;
private Node right;
// 0 指向的是子树,1表示指向的是节点
private int leftType;
private int rightType;
public Node(int no, String name) {
this.no = no;
this.name = name;
}
// 省略get、set
}
标签:Node,node,private,二叉树,root,节点
From: https://www.cnblogs.com/viva-zzt/p/17071021.html