题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
实现
中序遍历二叉搜索树就可以,需要记录节点的前一个指针。同时需要标记下是否是双向链表的头节点
public TreeNode Convert(TreeNode root) {
Stack<TreeNode> stack=new Stack<TreeNode>();
TreeNode newroot=null;
TreeNode pre=null;
boolean isfirst=true;
while(!stack.isEmpty() || root!=null){
while(root!=null){
stack.push(root);
root=root.left;
}
if(!stack.isEmpty()){
root=stack.pop();
if(isfirst){
newroot=root;
pre=newroot;
isfirst=false;
}
else{
root.left=pre;
pre.right=root;
pre=root;
}
root=root.right;
}
}
return newroot;
}