剑指offer 49. 二叉搜索树与双向链表- java
AcWing 49. 二叉搜索树与双向链表
原题链接
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。
要求不能创建任何新的结点,只能调整树中结点指针的指向。
注意:
需要返回双向链表最左侧的节点。
例如,输入下图中左边的二叉搜索树,则输出右边的排序双向链表。
题解
就在中序递归遍历的基础上改了一点点,用一个pre指针保存中序遍历的前一个结点。
因为是中序遍历,遍历顺序就是双线链表的建立顺序;
每一个结点访问时它的左子树肯定被访问过了,所以放心大胆的改它的left指针,不怕树断掉;
同理,pre指向的结点保存的数肯定小于当前结点,所以其左右子树肯定都访问过了,所以其right指针也可以直接改。
最后需要一直向左找到双向链表的头结点。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode pre = null ;
public TreeNode convert(TreeNode root) {
dfs(root);
while(root !=null && root.left != null){
root = root.left;
}
return root ;//返回最左侧的结点
}
public void dfs( TreeNode root){//按照中序遍历的方式
if(root == null ){
return ;
}
dfs(root.left);//遍历左侧点
root.left = pre ;//建立连接
if(pre != null){
pre.right = root; //建立连接 还要判断一下
}
pre = root ;//更新结点 遍历中心根节点
dfs(root.right);//遍历右节点
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode convert(TreeNode root) {
TreeNode pre=null;
dsf(pre,root);
while (root!=null&&root.left!=null)
root=root.left;
return root;
}
private TreeNode dsf(TreeNode pre, TreeNode root) {
if (root==null)
return pre;
pre=dsf(pre,root.left);
root.left=pre;
if (pre!=null)
pre.right=root;
pre=dsf(root,root.right);
return pre;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)