博客
关于我
剑指offer(牛客)---26.二叉搜索树与双向链表
阅读量:717 次
发布时间:2019-03-17

本文共 1170 字,大约阅读时间需要 3 分钟。

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

牛客推荐代码如下:

public class Solution {    public TreeNode Convert(TreeNode pRootOfTree) {        if (pRootOfTree == null) return null;        if (pRootOfTree.left == null && pRootOfTree.right == null) return pRootOfTree;        // 1. 将左子树构造成双链表,并返回链表头节点        TreeNode left = Convert(pRootOfTree.left);        TreeNode p = left;        // 2. 定位至左子树双链表最后一个节点        while (p != null && p.right != null) {            p = p.right;        }        // 3. 如果左子树链表不为空,当前root追加到左子树链表        if (left != null) {            p.right = pRootOfTree;            pRootOfTree.left = p;        }        // 4. 将右子树构造成双链表,并返回链表头节点        TreeNode right = Convert(pRootOfTree.right);        // 5. 如果右子树链表不为空,将该链表追加到root节点之后        if (right != null) {            right.left = pRootOfTree;            pRootOfTree.right = right;        }        return left != null ? left : pRootOfTree;    }}

解题思路:假设有如下二叉搜索树:

6      /   \    5      7   / \     / \  3   8   14  25

第一次递归处理左子树,构建成双链表并返回链表头节点。然后定位到左子树最后一个节点,并将当前节点6追加到左子树链表中。接着递归处理右子树,同样将右子树构造成双链表并返回头节点,最后将该链表追加到节点6之后。

递归过程继续处理节点12的左子树,同样按照链表性质将节点12连接到链表末尾。这一过程类似于顺序遍历二叉树,但借助递归实现,巧妙地将树结构转换为链表形式。

转载地址:http://oubhz.baihongyu.com/

你可能感兴趣的文章
PIL&QOOT;IOERROR:带有大图像的图像文件被截断(&Q)
查看>>
PIL.Image、cv2的img、bytes相互转换
查看>>
PIL.Image进行图像融合显示(Image.blend)
查看>>
Pillow lacks the JPEG 2000 plugin
查看>>
SpringBoot之ElasticsearchRestTemplate常用示例
查看>>
ping 全网段CMD命令
查看>>
ping 命令的七种用法,看完瞬间成大神
查看>>
Pinia:$patch的使用场景
查看>>
Pinia:$subscribe()的使用场景
查看>>
Pinpoint对Kubernetes关键业务模块进行全链路监控
查看>>
Pinterest 大规模缓存集群的架构剖析
查看>>
pintos project (2) Project 1 Thread -Mission 1 Code
查看>>
PinYin4j库的使用
查看>>
PIP
查看>>
pip install goose-extractor // SyntaxError: Missing parentheses in call to 'print'
查看>>
pip install mysqlclient报错
查看>>
pip install 出现报asciii码错误的解决
查看>>
pip throws TypeError: parse() got an unexpected keyword argument ‘transport_encoding‘ 在尝试安装新软件包时
查看>>
pip 下载慢
查看>>
pip 升级报错AttributeError: ‘NoneType’ object has no attribute ‘bytes’
查看>>