二叉搜索树与双向链表Java

本文介绍如何将一棵二叉搜索树转换为排序的双向链表,通过调整树中结点指针方向实现,无需创建新结点。文章提供了一个具体的实现案例,包括递归转换过程和遍历展示。

题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的方向。

思路:在二叉搜索树中,左子结点的值总是小于父子结点的值,右子结点的值总是大于父结点的值。因此在转换成排序的双向链表时,原先指向左子节点的值调整为 链表中指向前一个结点的指针,原先指向右子结点的指针调整为链表中指向后一个结点的指针。


根结点,左子树和右子树。在把左,右子树都转换成排序的双向链表之后再和根结点连接起来,整棵二叉搜索树也就转换成了排序的双向链表。

package offer;
/**
 *二叉搜索树与双向链表 
 *输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何结点,只能调整树中结点指针的指向。
 */
public class Convert {
	public static void main(String[] args) {
		int[] pre={10,6,4,8,14,12,16};
		int[] inOrder = {4,6,8,10,12,14,16};
		BinaryTreeNode root = RebuildBinaryTree.rebuildBinaryTree(pre, inOrder);
		root.preOrder(root);
		BinaryTreeNode head = convert(root);
		BinaryTreeNode tail = null;
		System.out.println(head==null);
		while(head!=null){
			System.out.print(head.val+" ");
			tail = head;
			head = head.right;
		}
		System.out.println();
		while(tail!=null){
			System.out.print(tail.val+" ");
			tail = tail.left;
		}
	}
	
	public static BinaryTreeNode convert(BinaryTreeNode root){
		BinaryTreeNode lastNodeInList = null;
		lastNodeInList = convertNode(root,lastNodeInList);
		
		BinaryTreeNode headOfList = lastNodeInList;
		while(headOfList!=null && headOfList.left!=null){
			headOfList = headOfList.left;
		}
		return headOfList;
	}
	public static BinaryTreeNode convertNode(BinaryTreeNode node, BinaryTreeNode lastNodeInList){
		if(node==null)
			return null;
		BinaryTreeNode current = node;
		if(current.left!=null)
			lastNodeInList = convertNode(current.left,lastNodeInList);
		current.left = lastNodeInList;
		if(lastNodeInList!=null)
			lastNodeInList.right = current;
		lastNodeInList = current;
		if(current.right!=null)
			lastNodeInList = convertNode(current.right,lastNodeInList);
		return lastNodeInList;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值