AcWing 49. 二叉搜索树与双向链表
原题链接
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。
要求不能创建任何新的结点,只能调整树中结点指针的指向。
注意:
需要返回双向链表最左侧的节点。
例如,输入下图中左边的二叉搜索树,则输出右边的排序双向链表。
题解
就在中序递归遍历的基础上改了一点点,用一个pre指针保存中序遍历的前一个结点。
因为是中序遍历,遍历顺序就是双线链表的建立顺序;
每一个结点访问时它的左子树肯定被访问过了,所以放心大胆的改它的left指针,不怕树断掉;
同理,pre指向的结点保存的数肯定小于当前结点,所以其左右子树肯定都访问过了,所以其right指针也可以直接改。
最后需要一直向左找到双向链表的头结点。
leetcode上面是双向循环链表
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val,Node _left,Node _right) {
val = _val;
left = _left;
right = _right;
}
};
*/
class Solution {
//循环链表
Node pre = null ;Node head = null;
public Node treeToDoublyList(Node root) {
if(root == null) return null ;
dfs(root);
head.left = pre; pre.right = head;
return head ;
}
void dfs(Node root){
if(root == null ) return ;
dfs(root.left);//遍历左侧点
root.left = pre;
if(pre != null){
pre.right = root; //建立连接 还要判断一下
}else head = 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 {
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;
}
}