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

牛客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;
    }
}
相关推荐
ballball~~26 分钟前
拉普拉斯金字塔
算法·机器学习
Cemtery11627 分钟前
Day26 常见的降维算法
人工智能·python·算法·机器学习
Ethan-D2 小时前
#每日一题19 回溯 + 全排列思想
java·开发语言·python·算法·leetcode
Benny_Tang2 小时前
题解:CF2164C Dungeon
c++·算法
仙俊红2 小时前
LeetCode174双周赛T3
数据结构·算法
橘颂TA3 小时前
【剑斩OFFER】算法的暴力美学——LeetCode 733 题:图像渲染
算法·leetcode·职场和发展
不穿格子的程序员3 小时前
从零开始写算法——回溯篇2:电话号码的字母组合 + 组合总和
算法·深度优先·回溯
仍然.3 小时前
JavaDataStructure---二叉搜索树,哈希表,Map和Set
数据结构·散列表
持梦远方3 小时前
算法剖析1:摩尔投票算法 ——寻找出现次数超过一半的数
c++·算法·摩尔投票算法
程序员-King.3 小时前
链表——算法总结与新手教学指南
数据结构·算法·链表