[4]《剑指offer》二叉搜索树与双向链表

本文介绍如何将一棵二叉搜索树转换为排序的双向链表,提供了两种实现方式:非递归和递归算法。非递归方法通过中序遍历调整节点指针,递归方法则通过构造左右子树链表并连接。

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

注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注

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

方法一:非递归版
解题思路:
1.核心是中序遍历的非递归算法。
2.修改当前遍历节点与前一遍历节点的指针指向。

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

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

    }

}
*/
import java.util.Stack;
public class Solution {
    public TreeNode Convert(TreeNode root) {
        if (root == null) return null;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode pre = null;
        boolean isHead = true;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            // pre = null
            // cur = first node of in-order sequence
            if (isHead) {
                root = cur; // set first node of in-order sequence to root
                isHead = false;
            } else {
                pre.right = cur;
                cur.left = pre;
            }
            pre = cur;
            cur = cur.right;
        }
        return root;
    }
}

方法二:递归
解题思路:
1.将左子树构造成双链表,并返回链表头节点。
2.定位至左子树双链表最后一个节点。
3.如果左子树链表不为空的话,将当前root追加到左子树链表。
4.将右子树构造成双链表,并返回链表头节点。
5.如果右子树链表不为空的话,将该链表追加到root节点之后。
6.根据左子树链表是否为空确定返回的节点。

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

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

    }

}
*/

public class Solution {
    public TreeNode Convert(TreeNode root) {
        if (root == null) return null;
        if (root.left == null && root.right == null) {
            return root;
        }
        //1.将左子树构造成双链表,并返回链表头节点。
        TreeNode left = Convert(root.left);
        TreeNode cur = left;    
        //2.定位至左子树双链表最后一个节点。
        while (cur != null && cur.right != null) {
            cur = cur.right;
        }
        //3.如果左子树链表不为空的话,将当前root追加到左子树链表。
        if (left != null) {
            cur.right = root;
            root.left = cur;
        }
        //4.将右子树构造成双链表,并返回链表头节点。
        TreeNode right = Convert(root.right);
        //5.如果右子树链表不为空的话,将该链表追加到root节点之后。
        if (right != null) {
            right.left = root;
            root.right = right;
        }
        //6.根据左子树链表是否为空确定返回的节点。
        return left == null ? root : left;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值