题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
/**
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 head1 = Convert(pRootOfTree.left);
if(head1!=null){
//找左子树最后一个节点
TreeNode lst = findLastNode(head1);
//链接左子树、根
lst.right = pRootOfTree;
pRootOfTree.left = lst;
}
//右子树转换
TreeNode head2 = Convert(pRootOfTree.right);
if(head2!=null){
//链接右子树、根
pRootOfTree.right = head2;
head2.left = pRootOfTree;
}
if(head1!=null){
return head1;
}else{
return pRootOfTree;
}
}
public TreeNode findLastNode(TreeNode head){
TreeNode lst = head;
while(lst.right!=null){
lst = lst.right;
}
return lst;
}
}
网友评论