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

题目描述

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

思路:采用中序遍历的思想(二叉搜索树中序遍历有序)。假设某一时刻遍历到根结点(结点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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值