/**
* 功能:输入一颗二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树种结点指针的指向。
* 比如输入图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
}
}
【笔试】44、二叉搜索树与双向链表
最新推荐文章于 2018-07-24 17:49:05 发布