输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
private TreeNode2 lca = null;
public TreeNode2 lowestCommonAncestor(TreeNode2 root, TreeNode2 p, TreeNode2 q) {
if (root == null){
return null;
}
findNode(root,p,q);
return lca;
}
//看从root出发能不能找到p和q
private boolean findNode(TreeNode2 root, TreeNode2 p, TreeNode2 q) {
if (root == null){
return false;
}
int left = findNode(root.left,p,q)?1:0;
int right = findNode(root.right,p,q)?1:0;
int mid = (root == p || root == q)?1:0;
if (left + right + mid == 2){
lca = root;
}
return (left + right + mid)>0;
}
//输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
//中序遍历
public TreeNode2 Convert(TreeNode2 pRootOfTree) {
if (pRootOfTree == null){
return null;
}
if (pRootOfTree.left == null && pRootOfTree.right == null){
return pRootOfTree;
}
//最终的链表 =》 左子树链表 + 根节点 + 右子树的链表
//1.先递归处理左子树
//left就是左子树这个链表的根节点
TreeNode2 left = Convert(pRootOfTree.left);
//2.需要找到左子树链表的尾节点
//right相当于链表的next
TreeNode2 leftTail = left;
while (leftTail != null && leftTail.right != null){
leftTail = leftTail.right;
}
//循环结束之后,leftTail就指向了左侧链表的尾部
//3.把左子树和当前节点连在一起
if (left != null){
leftTail.right = pRootOfTree;
pRootOfTree.left = leftTail;
}
//4.递归转换右子树,把右子树也变成双向链表
TreeNode2 right = Convert(pRootOfTree.right);
//5.把当前节点和右子树连在一起
if (right != null){
right.left = pRootOfTree;
pRootOfTree.right = right;
}
//6.最终返回新的链表的头节点
return left == null ? pRootOfTree : left;
}