第一题 leetcode原题 反转链表二
反转链表II
第二题
将一棵二叉搜索树转换成有序双向链表
因为二叉搜索树的中序遍历是有序的。
首先找到最左边的节点,保存好,这个节点就是我们要返回的双向链表的头节点。
在转换的过程中,我们使用一个分治的思想
先将左子树转换成一个有序双向链表,然后将左子树的尾节点与根节点相连,再将右子树转换后的链表与根节点相连,这样就通过中序构成了一个有序双向链表
最后返回之前保存好的头节点
class Solution {
Node res = null;
public void dfs(Node root){
while (root != null && root.left != null){
root = root.left;
}
res = root;
}
public Node help(Node root){
if (root == null){
return null;
}
Node left = help(root.left);
Node right = help(root.right);
if (left == null && right == null){
return root;
}
Node n = left;
root.left = root.right = null;
if (left != null){
while (left.right != null){
left = left.right;
}
left.right = root;
root.left = left;
}else{
n = root;
}
if (right != null){
root.right = right;
right.left = root;
}
return n;
}
/* Write Code Here */
public Node Convert(Node pRootOfTree) {
dfs(pRootOfTree);
help(pRootOfTree);
return res;
}
}```