剑指offer 二叉搜索树与双向链表
描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
大概思路
树节点有两个指针,可改为双向链表节点的前后指针。
需要转成排序的双向链表,因为二叉搜索树的特性:中序遍历就是节点值排序结果。
所以考虑,非递归法中序遍历二叉树。
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
public TreeNode Convert(TreeNode root) {
if(root==null)
return null;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root;
TreeNode pre = null;// 用于保存中序遍历序列的上一节点
boolean isFirst = true; //判断是否是第一个节点
while(p!=null||!stack.isEmpty()){
while(p!=null){
stack.push(p);
p = p.left;
}
p = stack.pop();
if(isFirst){
root = p;// 将中序遍历序列中的第一个节点记为root
pre = root;// pre先指向root
isFirst = false;
}else{
pre.right = p;
p.left = pre;
pre = p; //pre始终指向中序遍历的前一个节点
}p = p.right;
}
return root;
}
}