思路:
- 将左子树构造成双链表,并返回表头结点;
- 定位至左子树双链表的最后一个结点;
- 如果左子树链表不为空的话,把root追加到链表;
- 将右子树构造成双链表,并返回表头结点;
- 如果右子树链表不为空的话,把该链表追加到root之后;
- 根据左子树链表是否为空返回要求的结点。
/**
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;
}
if(pRootOfTree.left == null && pRootOfTree.right == null){
return pRootOfTree;
}
//将左子树构造成双链表并返回链表头结点
TreeNode left = Convert(pRootOfTree.left);
TreeNode p = left;
//定位至左子树双链表最后一个结点
while(p!=null && p.right!=null){
p = p.right;
}
//如果左子树链表不为空的话,将当前root追加到左子树链表
if(left != null){
p.right = pRootOfTree;
pRootOfTree.left = p;
}
//将右子树构造成双链表并返回表头结点
TreeNode right = Convert(pRootOfTree.right);
//如果右子树链表不为空的话,将该链表追加到root之后
if(right != null){
right.left = pRootOfTree ;
pRootOfTree.right = right ;
}
return left != null?left:pRootOfTree;
}
}
Convert() ???
递归、中序遍历:
//递归调用 左 根 右 遍历
public class Solution {
//双向链表的左边头结点和右边头节点
TreeNode leftHead = null;
TreeNode rightHead = null;
public TreeNode Convert(TreeNode pRootOfTree) {
//递归调用叶子节点的左右节点返回null
if(pRootOfTree==null) return null;
//第一次运行时,它会使最左边叶子节点为链表第一个节点
Convert(pRootOfTree.left);
if(rightHead==null){
leftHead= rightHead = pRootOfTree;
}else{
//把根节点插入到双向链表右边,rightHead向后移动
rightHead.right = pRootOfTree;
pRootOfTree.left = rightHead;
rightHead = pRootOfTree;
}
//把右叶子节点也插入到双向链表(rightHead已确定,直接插入)
Convert(pRootOfTree.right);
//返回左边头结点
return leftHead;
}
}