题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
TreeNode pre=null;
TreeNode head=null;
public TreeNode Convert(TreeNode pRootOfTree) {
convertList(pRootOfTree);
return head;
}
//中序遍历BST
public void convertList(TreeNode node){
if(node==null)return;
//中序遍历左子树
convertList(node.left);
node.left=pre;
if(pre!=null)pre.right=node;
//中序遍历根节点
pre=node;
//中序遍历右子树
if(head==null)head=node;
convertList(node.right);
}
}