题目
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。
要求不能创建任何新的结点,只能调整树中结点指针的指向。
注意:
需要返回双向链表最左侧的节点。
例如,输入下图中左边的二叉搜索树,则输出右边的排序双向链表。
算法:
class Solution {
public TreeNode convert(TreeNode root) {
if(root == null) return root;
Pair<TreeNode,TreeNode> res = dfs(root);
return res.getKey();
}
public Pair<TreeNode,TreeNode> dfs(TreeNode root){
if(root.left == null && root.right == null){
return new Pair<TreeNode,TreeNode>(root,root);
}
if(root.left != null && root.right != null){
Pair<TreeNode,TreeNode> lside = dfs(root.left),rside = dfs(root.right);
lside.getValue().right = root;
root.left = lside.getValue().right;
rside.left = root;
root.right = rside.left;
return new Pair<TreeNode,TreeNode>(lside.getValue,rside.getKey);
}
if(root.left != null && root.right == null){
Pair<TreeNode,TreeNode> lside = dfs(root.left);
lside.getValue().right = root;
root.left = lside.getValue().right;
return new Pair<TreeNode,TreeNode>(lside.getValue,root);
}
if(root.left == null && root.right != null){
Pair<TreeNode,TreeNode> rside = dfs(root.right);
rside.left = root;
root.right = rside.left;
return new Pair<TreeNode,TreeNode>(root,rside.getKey);
}
}
}
class Solution {
TreeNode pre = null;
public TreeNode convert(TreeNode root) {
if(root == null) return null;
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);
}
}