二叉搜索树转化成双向链表
发布日期:2021-06-30 19:56:23
浏览次数:2
分类:技术文章
本文共 1189 字,大约阅读时间需要 3 分钟。
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
题目链接:
其中一个测试用例:
{10,6,14,4,8,12,16}(按层序遍历输入) 对应输出应该为:From left to right are:4,6,8,10,12,14,16;From right to left are:16,14,12,10,8,6,4;
思路:
根节点的处理:
这种思路类似于线索二叉树的中序遍历,只是没有标志域。
AC代码:
/**public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}*/public class Solution { private TreeNode pre = null; // 因为没有二级指针,只能用全局变量了 public TreeNode Convert(TreeNode pRootOfTree) { if (pRootOfTree == null) return null; if (pRootOfTree.left == null && pRootOfTree.right == null) return pRootOfTree; LinkedNode(pRootOfTree); TreeNode cur = pRootOfTree; while (cur.left != null) { cur = cur.left; } return cur; } private void LinkedNode(TreeNode root) { if (root.left != null) { LinkedNode(root.left); } root.left = pre; if (pre != null) pre.right = root; pre = root; if (root.right != null) { LinkedNode(root.right); } }}
=====================Talk is cheap, show me the code======================
转载地址:https://liuchenyang0515.blog.csdn.net/article/details/85097631 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
很好
[***.229.124.182]2024年04月16日 17时07分46秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
python 函数式编程
2019-04-30
python编码
2019-04-30
scala maven plugin
2019-04-30
flink 1-个人理解
2019-04-30
redis cli
2019-04-30
redis api
2019-04-30
flink physical partition
2019-04-30
java 解析json
2019-04-30
java http请求
2019-04-30
tensorflow 数据格式
2019-04-30
tf rnn layer
2019-04-30
tf input layer
2019-04-30
tf model create
2019-04-30
tf dense layer两种创建方式的对比和numpy实现
2019-04-30
tf initializer
2021-07-03
tf 从RNN到BERT
2021-07-03
tf keras SimpleRNN源码解析
2021-07-03
tf keras Dense源码解析
2021-07-03
tf rnn输入输出的维度和权重的维度
2021-07-03