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

本文介绍如何将一棵二叉搜索树转换为排序的双向链表,使用递归中序遍历的方法,通过调整节点间的指针指向实现转换过程,避免创建新节点。

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

题目描述

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

实验平台:牛客网


解决思路:

这里写图片描述
这里写图片描述
这里写图片描述

java:

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    TreeNode lastNode = null;

    public TreeNode Convert(TreeNode pRootOfTree) {
        convertNode(pRootOfTree);
        TreeNode headNode = lastNode;
        while (headNode != null && headNode.left != null) {
            headNode = headNode.left;
        }
        return headNode;
    }

    public void convertNode(TreeNode node) {
        if (node == null) {
            return;
        }
        TreeNode curNode = node;
        if (curNode.left != null) {
            convertNode(curNode.left);
        }

        if (lastNode != null) {
            lastNode.right = curNode;
            curNode.left = lastNode;
        }
        lastNode = curNode;
        if (curNode.right != null) {
            convertNode(curNode.right);
        }
    }
}

python:

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    last_node = None

    def Convert(self, pRootOfTree):
        # write code here
        self.convert_node(pRootOfTree)
        head_node = self.last_node
        while head_node is not None and head_node.left is not None:
            head_node = head_node.left
        return head_node

    def convert_node(self, node):
        if node is None:
            return
        cur_node = node
        if cur_node.left is not None:
            self.convert_node(cur_node.left)
        if self.last_node is not None:
            self.last_node.right = cur_node
            cur_node.left = self.last_node
        self.last_node = cur_node
        if cur_node.right is not None:
            self.convert_node(cur_node.right)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值