博客
关于我
剑指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/

你可能感兴趣的文章
POJ 3041 Asteroids(二分匹配模板题)
查看>>
Qt笔记——标准文件对话框QFileDialog
查看>>
poj 3083 Children of the Candy Corn
查看>>
POJ 3083 Children of the Candy Corn 解题报告
查看>>
POJ 3253 Fence Repair C++ STL multiset 可解 (同51nod 1117 聪明的木匠)
查看>>
Qt笔记——控件总结
查看>>
poj 3262 Protecting the Flowers 贪心
查看>>
poj 3264(简单线段树)
查看>>
Qt笔记——布局管理三件套分割窗口、停靠窗口和堆栈窗口
查看>>
poj 3277 线段树
查看>>
POJ 3349 Snowflake Snow Snowflakes
查看>>
POJ 3411 DFS
查看>>
poj 3422 Kaka's Matrix Travels (费用流 + 拆点)
查看>>
Qt笔记——官方文档全局定义(二)Functions函数
查看>>
POJ 3468 A Simple Problem with Integers
查看>>
poj 3468 A Simple Problem with Integers 降维线段树
查看>>
poj 3468 A Simple Problem with Integers(线段树 插线问线)
查看>>
poj 3485 区间选点
查看>>
poj 3518 Prime Gap
查看>>
poj 3539 Elevator——同余类bfs
查看>>