题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
递归法:
/**
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.right!=null){//当右边不为空时,将有边子链排列好,将右端和根节点相连
pRootOfTree.right=Convert(pRootOfTree.right);
pRootOfTree.right.left=pRootOfTree;
}
if(pRootOfTree.left==null)//当左端为空时,返回根节点
return pRootOfTree;
else{//当左端不为空时,将左端排列好,再将左端尾部和根节点相连,返回左端头
pRootOfTree.left=Convert(pRootOfTree.left);
TreeNode temp=pRootOfTree.left;
while(temp.right!=null)
temp=temp.right;
temp.right=pRootOfTree;
TreeNode Left=pRootOfTree.left;
pRootOfTree.left=temp;
return Left;
}
}
}
直接中序遍历:
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
//直接用中序遍历
public class Solution {
TreeNode head = null;
TreeNode realHead = null;
public TreeNode Convert(TreeNode pRootOfTree) {
ConvertSub(pRootOfTree);
return realHead;
}
private void ConvertSub(TreeNode pRootOfTree) {
if(pRootOfTree==null) return;
ConvertSub(pRootOfTree.left);
if (head == null) {
head = pRootOfTree;
realHead = pRootOfTree;
} else {
head.right = pRootOfTree;
pRootOfTree.left = head;
head = pRootOfTree;
}
ConvertSub(pRootOfTree.right);
}
}