【笔试】44、二叉搜索树与双向链表

/**
 * 功能:输入一颗二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树种结点指针的指向。
 * 		比如输入图4.12中左边的二叉搜索树,则输出转换之后的排序双向链表。
 * 时间:2015年9月18日08:39:43
 * 文件:ConvertBinarySearchTree.java
 * 作者:cutter_point
 */
package bishi.Offer50.y2015.m09.d18;

import bishi.Offer50.y2015.m08.d26.*;

public class ConvertBinarySearchTree
{
	private BinaryTreeNode pLastNodeInList;
	
	/**
	 * 这个函数把树转化为链表
	 * @param pRootOfTree
	 * @return
	 */
	public BinaryTreeNode convert(BinaryTreeNode pRootOfTree)
	{
		if(pRootOfTree == null)
			return null;
		pLastNodeInList = null;
		convertNode(pRootOfTree);
		//这个转换完成之后,我们的pLastNodeInList指向最后一个节点
		BinaryTreeNode head = pLastNodeInList;
		//这个时候向前遍历,到头节点
		while(head.m_pLeft != null)
		{
			head = head.m_pLeft;
		}//while
		
		return head;
	}
	
	/**
	 * 这个是对我们的树进行转化为链表的函数
	 * @param pNode
	 * @param pLastNodeInList
	 */
	private void convertNode(BinaryTreeNode pNode)
	{
		if(pNode == null)
			return;
		
		BinaryTreeNode pCurrent = pNode;	//代表当前节点
		if(pCurrent.m_pLeft != null)
		{
			//如果左子树没有到达中序遍历的结果,那么就递归下去
			convertNode(pCurrent.m_pLeft);
		}//if
		
		//如果左边已经到了最后的节点
		pCurrent.m_pLeft = pLastNodeInList;	//把左边的指针指向上一个节点
		//如果我们的上一个父节点节点的指向不为空,那么我们把当前节点的右指针指向父节点
		if(pLastNodeInList != null)
		{
			pLastNodeInList.m_pRight = pCurrent;
		}//if
		
		//从新给上次遍历最后一个遍历的节点赋值
		pLastNodeInList = pCurrent;
		//遍历完左边,遍历右边,处理完左子树
		if(pCurrent.m_pRight != null)
		{
			convertNode(pCurrent.m_pRight);
		}//if
		
	}
	
	public static void main(String[] args)
	{
		int preorder[] = {10,6,4,8,14,12,16};
		int inorder[] = {4,6,8,10,12,14,16};
		BinaryTree bt = new BinaryTree();
		bt.construct(preorder, inorder);
		BinaryTreeNode test = bt.root;
		ConvertBinarySearchTree cbst = new ConvertBinarySearchTree();
		BinaryTreeNode head = cbst.convert(test);
		BinaryTreeNode pNode = head;
		while(pNode != null)
		{
			System.out.print(pNode.m_nValue + "\t");
			pNode = pNode.m_pRight;
		}//while
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值