二叉搜索树的特点:
左节点比根节点小
右节点比根节点大
如果要构建一个有序的双向链表,很容易想到其实顺序就是二叉树的中序遍历
需要思考的点在于,怎么将这些节点互相连起来
对于每一个小的节点来说,就是左-根-右 然后就要获取上一个节点的根结点
这里我们想到了用栈的结构来实现整个需求
即先遍历左子树,把左子树所有的根结点都入栈,然后每次出栈之后,把自己的左右节点连起来以后,再去连下一个出栈的节点就可以了
import java.util.Stack;
public class TreeToDoubleLink {
public static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public static TreeNode Convert(TreeNode treeNode){
TreeNode currentNode = treeNode;
TreeNode node = null;
TreeNode head = null; //等一下的链表头,也就是左子树的最左的那个节点
Stack<TreeNode> stack = new Stack<>();
while((currentNode != null) || !stack.isEmpty()){
if(currentNode != null){
stack.push(currentNode);
currentNode = currentNode.left;
}
else{
currentNode = stack.pop();
//获取链表头
if(node == null){
node = currentNode;
head = node;
}
else{
node.right = currentNode;
currentNode.left = node;
node = node.right;
}
currentNode = currentNode.right;
}
}
return head;
}
}
反正思路的核心就是,要将下一个要访问的根结点入栈。