java实现二叉搜索树转双向链表

/**
 * 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
 * 
 * @author pomay
 *
 */
class Solution_treetolist
{

	public TreeNode Convert(TreeNode pRootOfTree)
	{
		TreeNode lastNodeOfList = null;// LastNodeOfList指向已经转换好的链表的最后一个结点
		// 返回头结点
		TreeNode headNodeOfList = ConvertNode(pRootOfTree, lastNodeOfList);
		// 一直倒退到头结点
		while (headNodeOfList != null && headNodeOfList.left != null)
			headNodeOfList = headNodeOfList.left;

		return headNodeOfList;
	}

	// 把二叉树转换成链表,获得链表最后结点(即最大结点)
	TreeNode ConvertNode(TreeNode pNode, TreeNode LastNodeOfList)
	{
		if (pNode == null)
			return null;
		TreeNode current = pNode;

		if (current.left != null)
			// 把左子树转成链表
			LastNodeOfList = ConvertNode(current.left, LastNodeOfList);
		// 当前结点的左边就是左子树构成的链表的最后一个结点
		current.left = LastNodeOfList;

		if (LastNodeOfList != null)
			// 把转换好的链表后面连接当前结点
			LastNodeOfList.right = current;
		// 此时根转换好的链表最后一个结点就是当前结点
		LastNodeOfList = current;
		// 同理 把右子树转成链表
		if (current.right != null)
			LastNodeOfList = ConvertNode(current.right, LastNodeOfList);
		return LastNodeOfList;
	}

	public static void main(String[] args)
	{
		TreeNode pRootOfTree = new TreeNode(10);
		pRootOfTree.left = new TreeNode(6);
		pRootOfTree.right = new TreeNode(14);
		pRootOfTree.left.left = new TreeNode(4);
		pRootOfTree.left.right = new TreeNode(8);
		pRootOfTree.right.left = new TreeNode(12);
		pRootOfTree.right.right = new TreeNode(16);

		Solution_treetolist treetolist = new Solution_treetolist();
		TreeNode result = treetolist.Convert(pRootOfTree);
		System.out.print(result.val + " " + result.right.val + " " + result.right.right.val + " "
				+ result.right.right.right.val + " " + result.right.right.right.right.val + " "
				+ result.right.right.right.right.right.val + " " + result.right.right.right.right.right.right.val);

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值