题目描述:
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
import java.util.Stack;
public class ConvertBSTreeToOrderBNode {
//非递归方法
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null){
return null;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = pRootOfTree;
Boolean isFirst = true;
TreeNode pHead = null;//排序的双向链表的头节点
TreeNode pre = pHead;// 记录前一个节点
while(p != null || !stack.isEmpty()){
while(p != null){
stack.push(p);
p = p.left;
}
p = stack.pop();
if(isFirst){
pHead = p;
pre = p;
isFirst = false;
}
else{
pre.right = p;
p.left = pre;
pre = p;
}
p = p.right;
}
return pHead;
}
//递归方法
public TreeNode Convert1(TreeNode pRootOfTree){
if(pRootOfTree == null){
return null;
}
if(pRootOfTree.left == null && pRootOfTree.right == null){
return pRootOfTree;
}
// 1.将左子树构造成双链表,并返回链表头节点
TreeNode leftHead = Convert(pRootOfTree.left);
TreeNode p = leftHead;
// 2.定位至左子树双链表最后一个节点
while(p != null && p.right != null){
p = p.right;
}
// 3.如果左子树链表不为空的话,将当前root追加到左子树链表
if(leftHead != null){
pRootOfTree.left = p;
p.right = pRootOfTree;
}
// 4.将右子树构造成双链表,并返回链表头节点
TreeNode rightHead = Convert(pRootOfTree.right);
// 5.如果右子树链表不为空的话,将该链表追加到root节点之后
if(rightHead != null){
rightHead.left = pRootOfTree;
pRootOfTree.right = rightHead;
}
return leftHead != null ? leftHead : pRootOfTree;
}
}