输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思想:利用非递归中序遍历思想
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;
}
本文介绍了一种不使用额外节点,仅通过调整二叉搜索树节点指针指向,将其转换为排序双向链表的方法。利用非递归中序遍历思想,实现了高效的转换过程。
625

被折叠的 条评论
为什么被折叠?



