面试题27:二叉排序树转双向链表

说明:

1.二叉排序树又名二叉搜索树;

2.二叉树转成的双向链表是排好序的;

3.总共有三种方法实现,但都是基于中序遍历。

(一)返回双向链表的头结点

// return the head of doubleLink
BinaryTreeNode convertToDoubleLink1(BinaryTreeNode currentRoot){
		if(currentRoot == null){
			return null;
		}
		// currentRoot not equal to null
		BinaryTreeNode leftHead = null;	
		if(currentRoot.left != null){
			leftHead = this.convertToDoubleLink1(currentRoot.left);
		}	
		if(leftHead != null){
			BinaryTreeNode leftTail = leftHead; 
			while(leftTail.right != null){
				leftTail = leftTail.right;
			}
			leftTail.right = currentRoot;
			currentRoot.left = leftTail;
		}
		
		BinaryTreeNode rightHead = null;
		if(currentRoot.right != null){
			rightHead = this.convertToDoubleLink1(currentRoot.right);
		}
		if(rightHead != null){
			rightHead.left = currentRoot;
			currentRoot.right = rightHead;
		}
		return leftHead != null? leftHead : currentRoot;
}

(二)返回双向链表的尾结点

//return the tail of doubleLink
BinaryTreeNode convertToDoubleLink2(BinaryTreeNode currentRoot){
		if(currentRoot == null){
			return null;
		}
		BinaryTreeNode leftTail = null;
		if(currentRoot.left != null){
			leftTail = this.convertToDoubleLink2(currentRoot.left);
		}
		if(leftTail != null){
			leftTail.right = currentRoot;
			currentRoot.left = leftTail;
		}
		
		BinaryTreeNode rightTail = null;
		if(currentRoot.right != null){
			rightTail = this.convertToDoubleLink2(currentRoot.right);
		}
		if(rightTail != null){
			BinaryTreeNode rightHead = rightTail;
			while(rightHead.left != null){
				rightHead = rightHead.left;
			}
			rightHead.left = currentRoot;
			currentRoot.right = rightHead;
		}
		return rightTail != null? rightTail : currentRoot;
}
(三)返回双向链表的头结点或者尾结点

// return the head or tail by asLeft
// if left tree return tail otherwise return head
BinaryTreeNode convertToDoubleLink(BinaryTreeNode t, boolean asLeft){
		
		if(t == null){
			return null;
		}
		// t not equal to null
		BinaryTreeNode pLeft = null;
		BinaryTreeNode pRight = null;
		if(t.left != null){
			pLeft = this.convertToDoubleLink(t.left, true);
		}
		if(pLeft != null){
			pLeft.right = t;
			t.left = pLeft;
		}
		if(t.right != null){
			pRight = this.convertToDoubleLink(t.right, false);
		}
		if(pRight != null){
			pRight.left = t;
			t.right = pRight;
		}
		
		BinaryTreeNode returnNode = t;
		if(asLeft){
			while(returnNode.right != null){
				returnNode = returnNode.right;
			}
		}else{
			while(returnNode.left != null){
				returnNode = returnNode.left;
			}
		}
		return returnNode;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值