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

本文介绍如何将二叉搜索树转换为排序的双向链表,通过中序遍历调整树节点指针实现转换,无需创建新节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二叉搜索树与双向链表

题目

输入一颗二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建新的结点,只能调整树中结点指针的指向。
class BinaryTreeNode {
int value;
BinaryTreeNode left;
BinaryTreeNode right;
}

思路

我们可以中序遍历树中的每一个结点,这是因为中序遍历算法的特点是按照从小到大的顺序遍历二叉树的每一个结点。

代码

public class BinaryTreeConvert {

    public BinaryTreeNode convert(BinaryTreeNode root) {
        //指向双向链表的尾节点
        BinaryTreeNode lastNodeInList = null;
        convertNode(root, lastNodeInList);

        //我们需要返回头结点
        BinaryTreeNode head = lastNodeInList;
        while(head != null && head.left != null){
            head = head.left;
        }
        return head;
    }

    //使用递归进行转换
    public void convertNode(BinaryTreeNode node, BinaryTreeNode lastNodeInList) {
        if(node == null)
            return ;

        BinaryTreeNode currentNode = node;
        //节点的左子节点不为空
        if(currentNode.left != null){
        //一直递归最左边的节点
            convertNode(currentNode.left, lastNodeInList);
        }
        
        currentNode.left = lastNodeInList;
        if(lastNodeInList != null){
            lastNodeInList.right = currentNode;
        }
        lastNodeInList = currentNode;
        if(currentNode.right != null){
            convertNode(currentNode.right, lastNodeInList);
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值