JAVA数据结构 双向链表转二叉树,每层按顺序放入值123456789

public static  ListNode<Integer> generateTree(ListNode<Integer> head,int c,ListNode<Integer> root ){
        if (null == head){
            return null;
        }else if(null == head.rightChi){      
            return new ListNode<>(head.val);
        }

        //这里使用快慢指针找到链表的中间节点
        ListNode<Integer> mid = null;
        ListNode<Integer> fast = head;
        ListNode<Integer> slow = head;
        while (null != fast && null!= fast.rightChi){
            fast= fast.rightChi.rightChi;
            mid = slow;
            slow = slow.rightChi;
        }
        //链表从中间打断
        mid.rightChi = null;
        ListNode<Integer> mRoot = new ListNode<>(mid.val);
        //遍历每层按节点从左到右放入依次123456789
        //c=1 代表左边节点赋值  c=2 代表右边节点赋值
        if (c==0){
            mRoot.val =1;
        }else if (c==1){
            mRoot.val = root.val*2;
        }else if (c==2){
            mRoot.val = root.val*2+1;
        }
        //左递归调用时传入当前root,用作下层计算放入的值mRoot.val*2
        mRoot.leftChi = generateTree(head,1,mRoot);
        mRoot.leftChi.father = mRoot;
        mRoot.leftChi.val = mRoot.val*2;

        //右递归调用时传入当前root,用作下层计算放入的值mRoot.val*2+1
        mRoot.rightChi = generateTree(slow.rightChi,2,mRoot);
        if (null != mRoot.rightChi){
            mRoot.rightChi.father = mRoot;
            mRoot.rightChi.val = mRoot.val*2+1;
        }
        return mRoot;
    }

树结构如图所示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值