剑指offer之面试题27:二叉搜索树与双向链表

来源:互联网 发布:实战nginx pdf 编辑:程序博客网 时间:2024/05/29 12:01

题目描述

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

思路:采用中序遍历的思想(二叉搜索树中序遍历有序)。假设某一时刻遍历到根结点(结点10),则此时左子树已经转化成双向链表,用一个指针指向此时的尾结点,现在可将原来的二叉搜索树看成三部分:已经转化好的左子树,根结点,未转化的右子树。且此时尾结点的值<根结点<右子树,我们可以把他们连起来,然后右子树继续转化。
而实际过程是从最左下的结点开始转化的,即转化左子树

if(pCurrent.left!=null){    pLastNodeInList=Convert(pCurrent.left,pLastNodeInList);}

链接转化后的左子树与根结点

root.left=pLastNodeOfList;if(pLastNodeOfList!=null){    pLastNodeOfList.right=root;}pLastNodeOfList=root;

然后右子树继续转化

if(root.right!=null){    pLastNodeInList=Convert(root.right,pLastNodeOfList);}

`完整代码如下:

/** *  */package com.su.biancheng;/** * @title Convert.java * @author Shuai * @date 2016-5-4下午2:11:57 */public class Convert {    public static class TreeNode{        int val;        TreeNode left=null;        TreeNode right=null;        TreeNode(int val){            this.val=val;        }    }    public static TreeNode Convert(TreeNode pRootOfTree) {        //pLastNodeInList 指向双向链表的尾结点        TreeNode pLastNodeInList=null;        pLastNodeInList=Convert(pRootOfTree,pLastNodeInList);        TreeNode pHeadOfList=pLastNodeInList;        //需要返回头结点        while(pHeadOfList!=null&&pHeadOfList.left!=null)            pHeadOfList=pHeadOfList.left;        return pHeadOfList;    }    public static TreeNode Convert(TreeNode pRootOfTree, TreeNode pLastNodeInList) {        if(pRootOfTree==null)            return null;        TreeNode pCurrent=pRootOfTree;        //递归左子树        if(pCurrent.left!=null)            pLastNodeInList=Convert(pCurrent.left,pLastNodeInList);        //左子树已经转化成双向链表,将左子树的最后一个结点与根结点链接起来        pCurrent.left=pLastNodeInList;        if(pLastNodeInList!=null)                       pLastNodeInList.right=pCurrent;        //链接后的结点为最后一个结点        pLastNodeInList=pCurrent;        //递归右子树        if(pCurrent.right!=null)            pLastNodeInList=Convert(pCurrent.right,pLastNodeInList);        return pLastNodeInList;    }    public static void main(String[] args){        TreeNode root=new TreeNode(10);        TreeNode node1=new TreeNode(6);        TreeNode node2=new TreeNode(14);        TreeNode node3=new TreeNode(4);        TreeNode node4=new TreeNode(8);        TreeNode node5=new TreeNode(12);        TreeNode node6=new TreeNode(16);        root.left=node1;        root.right=node2;        node1.left=node3;        node1.right=node4;        node2.left=node5;        node2.right=node6;        TreeNode node=Convert(root);        while(node!=null){            System.out.print(node.val+" ");            node=node.right;        }    }}
0 0