输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思想:利用非递归中序遍历思想
public TreeNode Convert(TreeNode pRootOfTree) {
if (pRootOfTree == null) {
return null;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode root = pRootOfTree;
TreeNode head = null;
TreeNode pre = null;
boolean isFirst = true;
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (isFirst) {
head = root;
pre = head;
isFirst = false;
} else {
pre.right = root;
root.left = pre;
pre = root;
}
root = root.right;
}
return head;
}