数据结构--线索二叉树

1、基本概念

普通的二叉树如果有n个节点,则有2n个指针域,有n-1条分支。那么有2n-(n-1)个指针域是空的。
如果想知道某个节点的前驱和后继,需要每次进行中序遍历,经常需要节点的前驱后继的话,效率不高。
可以使用空闲的指针域,分别指向节点的前驱和后继以提高效率。
这里写图片描述
如D的前驱是H,后继是I

2、实现

static class Node{
        int data;
        boolean isLeftThread;//true为左线索
        Node left;
        boolean isRightThread;
        Node right;

        public Node(int data) {
            this.data = data;
            this.isLeftThread = this.isRightThread = false;
            this.left = this.right = null;
        }
    }

    public static void main(String[] args) {
        int[] src = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        Node root = create(src, 1);
        System.out.println("中序递归遍历:");
        midList(root);
        System.out.println("\n中序线索遍历:");
        inThread(root);
        midTrav(root);
    }

    //构建完全二叉树
    public static Node create(int data[], int index){
        if(index > data.length)
            return null;

        Node node = new Node(data[index-1]);
        //完全二叉树 左子树为2*n  右子树为2*n+1
        node.left = create(data, 2*index);
        node.right = create(data, 2*index+1);

        return node;
    }

    private static Node pre = null;
    //二叉树线索化
    public static void inThread(Node node) {
        if(node != null) {
            inThread(node.left);
            if(node.left == null) {
                node.isLeftThread = true;
                node.left = pre;
            }

            if(pre!=null && pre.right==null) {
                pre.isRightThread = true;
                pre.right = node;
            }
            pre = node;
            inThread(node.right);
        }
    }

    //中序线索遍历
    public static void midTrav(Node node){
        if(node != null) {
            while(node!=null && !node.isLeftThread)
                node = node.left;

            do {
                System.out.print(node.data+"  ");

                if(node.isRightThread)
                    node = node.right;
                else {
                    node = node.right;
                    while (node!=null && !node.isLeftThread)
                        node = node.left;
                }

            } while (node!=null);
        }
    }

    public static void midList(Node root) {
        if (root != null) {
            midList(root.left);
            System.out.print(root.data + "  ");
            midList(root.right);
        }
    }

参考:
大话数据结构
http://blog.csdn.net/jiangnan2014/article/details/38656803

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值