输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
TreeNode head, pre;
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null) return null;
dfs(pRootOfTree);
return head;
}
public void dfs(TreeNode root){
if(root.left != null) dfs(root.left);
if(pre != null)pre.right = root;
else head = root;
root.left = pre;
pre = root;
if(root.right != null) dfs(root.right);
}
}

这篇博客详细介绍了如何将一棵二叉搜索树转换为一个排序的双向链表,通过深度优先搜索(DFS)策略,不创建新节点,只调整原有节点的指针。算法首先遍历左子树,然后连接前一个节点和当前节点,接着处理右子树,最终形成有序链表。
571

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



