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;
}
树结构如图所示