数据结构–线索化二叉树学习案例(java版)
该树结构如下(线索化前):
中序遍历方式
线索化后(虚线表示新加节点关系)
全部实现代码如下:
package com.mxf.ThreadBinaryTree;
public class ThreadBinaryTreeDemo {
public static void main(String[] args) {
//创建叶子节点
TreeNode root = new TreeNode(1, "A");
TreeNode node1 = new TreeNode(3, "B");
TreeNode node2 = new TreeNode(6, "C");
TreeNode node3 = new TreeNode(8, "D");
TreeNode node4 = new TreeNode(10, "E");
TreeNode node5 = new TreeNode(14, "F");
//还未学习递归创建树,先使用手动创建关联
node1.setLeftChild(node3);
node1.setRightChild(node4);
node2.setLeftChild(node5);
root.setLeftChild(node1);
root.setRightChild(node2);
ThreadBinaryTree threadBinaryTree = new ThreadBinaryTree();
threadBinaryTree.setRoot(root);
//线索化测试
threadBinaryTree.threadNodes();
//查看是否线索化成功
System.out.println(node4.getLeftChild());
System.out.println(node4.getRightChild());
}
}
//定义线索化二叉树
class ThreadBinaryTree {
private TreeNode root;
//保存每次操作节点的前一个节点
private TreeNode pre;
//重载threadNodes函数
public void threadNodes() {
this.threadNodes(root);
}
//线索化当前指向的节点
public void threadNodes(TreeNode node) {
if(node == null) return;
//线索化左子树
threadNodes(node.getLeftChild());
//线索化当前节点
//处理前驱结点
if(node.getLeftChild() == null) {
node.setLeftChild(pre);
node.setLeftType(1);
}
//处理后继节点
if(pre != null && pre.getRightChild() == null) {
pre.setRightChild(node);
pre.setRightType(1);
}
//处理pre的同步移动
pre = node;
//线索化右子树
threadNodes(node.getRightChild());
}
}
class TreeNode {
private int id;
private String name;
private TreeNode leftChild;
private TreeNode rightChild;
private static int count = 0;
private int leftType;
private int rightType;
public int getLeftType() {
return leftType;
}
public void setLeftType(int leftType) {
this.leftType = leftType;
}
public int getRightType() {
return rightType;
}
public void setRightType(int rightType) {
this.rightType = rightType;
}
public TreeNode(int id, String name) {
this.id = id;
this.name = name;
}
public static int getCount() {
return count;
}
public static void setCount(int count) {
TreeNode.count = count;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public TreeNode getLeftChild() {
return leftChild;
}
public void setLeftChild(TreeNode leftChild) {
this.leftChild = leftChild;
}
public TreeNode getRightChild() {
return rightChild;
}
public void setRightChild(TreeNode rightChild) {
this.rightChild = rightChild;
}
@Override
public String toString() {
return "TreeNode{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
如果看不太清楚,建议在 threadBinaryTree.threadNodes();该语句处设置断点,进行deBug几次,亲测有效有助于理解,这里的线索化用到了递归实现,希望能帮助到你,如果还有疑问可以留言