题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
解题思路:
与Lintcode 378. 将二叉查找树转换成双链表类似,不同的是这个不需要新建节点。
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null)
return null;
TreeNode left = Convert(pRootOfTree.left);
TreeNode right = Convert(pRootOfTree.right);
if(left != null){
TreeNode leftCur = left;
while(leftCur.right != null)
leftCur = leftCur.right;
pRootOfTree.left = leftCur;
leftCur.right = pRootOfTree;
}
if(right != null){
pRootOfTree.right = right;
right.left = pRootOfTree;
}
while(pRootOfTree.left != null)
pRootOfTree = pRootOfTree.left;
return pRootOfTree;
}
}