手撕算法-二叉搜索树与双向链表

牛客BM30。

描述:
https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5?tpId=295&tqId=23253&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj

分析:

二叉搜索树的中序遍历是递增序列。可以利用中序遍历完成。

同时不能新增节点,只能改变指针方向,left代表左,right代表右。

中序遍历时,会一次遍历从小到大的节点,此时记录前一个节点pre和当前节点cur,将:

pre.right = cur;

cur.left = pre;

pre = cur;

链接后的示意图(参考网图):

代码:

java 复制代码
public class Solution {
    TreeNode pre = null;

    TreeNode head = null;
    public TreeNode Convert(TreeNode pRootOfTree) {
        if (pRootOfTree == null) return pRootOfTree;
        TreeNode cur = pRootOfTree;
        //首先递归到最左最小值
        Convert(pRootOfTree.left);
        if (pre == null) {
            //找到最小值,初始化head与pre
            pre = cur;
            head = cur;
        } else {
            //当前节点与上一节点建立连接,将pre设置为当前值
            pre.right = cur;
            cur.left = pre;
            pre = cur;
        }
        Convert(pRootOfTree.right);

        return head;
    }
}
相关推荐
WBluuue1 小时前
数据结构与算法:摩尔投票算法
c++·算法·leetcode
2401_858286111 小时前
OS36.【Linux】简单理解EXT2文件系统(2)
linux·运维·服务器·数据结构·文件系统·ext2
小羊学伽瓦1 小时前
【Java数据结构】——常见力扣题综合
java·数据结构·leetcode·1024程序员节
文火冰糖的硅基工坊2 小时前
[人工智能-大模型-66]:模型层技术 - 两种编程范式:数学函数式编程与逻辑推理式编程,构建起截然不同的智能系统。
人工智能·神经网络·算法·1024程序员节
im_AMBER2 小时前
Leetcode 34
算法·leetcode
im_AMBER2 小时前
Leetcode 31
学习·算法·leetcode
吃着火锅x唱着歌3 小时前
LeetCode 74.搜索二维矩阵
算法·leetcode·矩阵
mit6.8243 小时前
hash|快速幂|栈
算法
OG one.Z3 小时前
06_决策树
算法·决策树·机器学习
爪哇部落算法小助手3 小时前
每日两题day23
算法