1.题目
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。

2.解法
2.1 树的结构
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
2.2 解法1
二叉搜索树的特点是左小右大。
考虑,返回的应该是这棵树最左孩子。即最小值。
因此先找到该节点。
并利用中序遍历梳理关系。
通过pre保存左子树、即最近访问过的值。
public class Solution {
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree==null) return null;
TreeNode left = pRootOfTree;
while (left.left!=null){
left = left.left;
}
helper(pRootOfTree);
return left;
}
TreeNode pre = null;
public void helper(TreeNode root) {
if (root == null) return ;
helper(root.left);
root.left = pre;
if(pre!=null) pre.right = root;
pre = root;
helper(root.right);
}
}
总结
考虑,返回的应该是这棵树最左孩子。即最小值。
算法系列在github上有一个开源项目,主要是本系列博客的demo代码。https://github.com/forestnlp/alg
如果您对软件开发、机器学习、深度学习有兴趣请关注本博客,将持续推出Java、软件架构、深度学习相关专栏。
您的支持是对我最大的鼓励。
本文介绍了如何将一棵二叉搜索树转换为排序的双向链表,利用中序遍历,找到最小值节点作为链表头,然后梳理各节点间的左右关系。算法实现包括关键步骤和代码示例,适合对数据结构和算法感兴趣的读者。
172万+

被折叠的 条评论
为什么被折叠?



