输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
import java.util.*;
public class Solution {
ArrayList<TreeNode> te = new ArrayList<TreeNode>();
public TreeNode Convert(TreeNode pRootOfTree) {
mid(pRootOfTree);
if (te.size()==0||te.size()==1) return pRootOfTree;
TreeNode fir = te.get(0);
fir.right = te.get(1);
fir.left = null;
for (int i=1;i<te.size()-1;i++){
TreeNode tem = te.get(i);//Arraylist不能直接通过索引访问;
tem.left = te.get(i-1);
tem.right = te.get(i+1);
}
TreeNode last = te.get(te.size()-1);
last.left = te.get(te.size()-2);
last.right = null;
return te.get(0);
}
private void mid(TreeNode pRootOfTree) {
//都需要加入判空条件,否则一不返回,二会在树中加入空值。
if(pRootOfTree==null){
return ;
}
if(pRootOfTree.left!=null){
mid(pRootOfTree.left);
}
te.add(pRootOfTree);
if(pRootOfTree.right!=null){
mid(pRootOfTree.right);
}
}
}
先中序遍历保存在数组中,然后遍历修改指针。