线索二叉树(数据结构)(中序线索为例)

public class ClueBinaryTree <T>{
    private ClueNode<T> pre;

    public class ClueNode<T>
    {
        private T data;
        public ClueNode<T> lChild;
        public ClueNode<T> rChild;
        public boolean ltag;
        public boolean rtag;
    }

    public ClueNode<T> head;
    public ClueBinaryTree(){
        this.head = new ClueNode<T>();
    }
    public boolean startInThreading(){//通过中序遍历对二叉树开始线索化
        if (head==null) return false;
        head.ltag = false;
        head.rtag = true;
        head.rChild=head;
        if (head.lChild == null){
            head.lChild = head;
        }else {
            pre = head;
            inThreading(head);
            pre.rChild = head;
            pre.rtag = true;
        }
        return true;
    }
    public void inThreading(ClueNode<T> node){//中序遍历宛城二叉树线索化
        if(node==null) return;
        inThreading(node.lChild);
        if (node.lChild==null){
            node.ltag = true;
            node.lChild = pre;
        }
        if (pre.rChild == null){
            pre.rtag = true;
            pre.rChild = node;
        }
        pre = node;
        inThreading(node.rChild);
    }

    public ClueNode<T> searchPreNode(ClueNode<T> node){//在中序线索二叉树上寻找节点node的中序前驱节点
        ClueNode<T> q = node.lChild;
        if(!node.ltag){
            while (!q.rtag)
                q = q.rChild;
        }
        return q;
    }
    public ClueNode<T> searchPostNode(ClueNode<T> node){//在中序二叉树上寻找节点node的中序后继节点
        ClueNode<T> q = node.rChild;
        if (!node.rtag)
            while (!q.rtag)
                q = q.lChild;
        return q;
    }
    public void display(){//按中序线索输出二叉树的数据元素
        ClueNode<T> node = head.lChild;
        if (node==null){//二叉树为空
            return;
        }
        while (!node.ltag){//寻找中序序列的首节点
            node = node.lChild;
        }do {
            if (node!=null){
                System.out.println(node.getData());
            }
            node = searchPostNode(node);//查找后继节点
        }
        while (node.rChild!=head);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值