题目链接:
解题思路:
1
.将左子树构造成双链表,并返回链表头节点。
2
.定位至左子树双链表最后一个节点。
3
.如果左子树链表不为空的话,将当前root追加到左子树链表。
4
.将右子树构造成双链表,并返回链表头节点。
5
.如果右子树链表不为空的话,将该链表追加到root节点之后。
6
.根据左子树链表是否为空确定返回的节点。
/*解题思路:
1.将左子树构造成双链表,并返回链表头节点。
2.定位至左子树双链表最后一个节点。
3.如果左子树链表不为空的话,将当前root追加到左子树链表。
4.将右子树构造成双链表,并返回链表头节点。
5.如果右子树链表不为空的话,将该链表追加到root节点之后。
6.根据左子树链表是否为空确定返回的节点。
*/
public class Solution {
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null){
return null;
}
if(pRootOfTree.left == null && pRootOfTree.right == null){
return pRootOfTree;
}
// 1.将左子树构造成双链表,并返回链表头节点
TreeNode left = Convert(pRootOfTree.left);
TreeNode p = left;
//2.定位至左子树双链表最后一个节点。
while(p != null && p.right !=null){
p = p.right;
}
//3.如果左子树链表不为空的话,将当前root追加到左子树链表。
if(left !=null){
p.right = pRootOfTree;
pRootOfTree.left = p;
}
//4.将右子树构造成双链表,并返回链表头节点。
TreeNode right = Convert(pRootOfTree.right);
//5.如果右子树链表不为空的话,将该链表追加到root节点之后。
if(right !=null){
pRootOfTree.right = right;
right.left = pRootOfTree;
}
//6.根据左子树链表是否为空确定返回的节点。
return left == null? pRootOfTree:left;
}
}
用了集合来存储中序遍历的结果:
import java.util.*;
public class Solution {
List<TreeNode> list = new ArrayList<>();
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null){
return null;
}
mid(pRootOfTree);
return convert();
}
public void mid(TreeNode root){
if(root != null){
if(root.left !=null){
mid(root.left);
}
list.add(root);
if(root.right !=null){
mid(root.right);
}
}
}
public TreeNode convert() {
int i = 0;
while(list.size() - 1 > i ){
list.get(i).right = list.get(i + 1);
list.get(i + 1).left = list.get(i);
i++;
}
return list.get(0);
}
}