题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思路:
不能创建新节点
肯定是中序遍历,麻烦的在于需要保持一个遍历过程中链表的尾巴,这样才能递归成链表
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode* Convert(TreeNode* pRootOfTree)
{
TreeNode* pLastNode=NULL;
ConvertCore(pRootOfTree,&pLastNode);
TreeNode* pHead=pLastNode;
while(pHead!=NULL&&pHead->left!=NULL)
pHead=pHead->left;
return pHead;
}
void ConvertCore(TreeNode* pNode,TreeNode** pLastNode)
{
if(pNode==NULL)
return;
TreeNode* pTmp=pNode;
if(pTmp->left!=NULL)
ConvertCore(pTmp->left,pLastNode);
pTmp->left=*pLastNode;//之前的结尾与本次的node互相链接
if(*pLastNode!=NULL)
(*pLastNode)->right=pTmp;
*pLastNode=pTmp;
if(pTmp->right!=NULL)
ConvertCore(pTmp->right,pLastNode);
}
};
java实现
import java.util.ArrayList;
public class Solution {
public TreeNode Convert(TreeNode pRootOfTree) {
if (pRootOfTree==null)
return null;
ArrayList<TreeNode> list=new ArrayList<>();
Convert(list,pRootOfTree);
return Convert(list);
}
public void Convert(ArrayList<TreeNode>list,TreeNode root){
if (root!=null){
Convert(list,root.left);
list.add(root);
Convert(list,root.right);
}
}
public TreeNode Convert(ArrayList<TreeNode<> list){
TreeNode head=list.get(0);
TreeNode cur=head;
for (int i=1;i<list.size();++i){
TreeNode node=list.get(i);
node.left=cur;
cur.right=node;
cur=node;
}
return head;
}
}
public class XiansuoTree {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(10);
root.left = new TreeNode(6);
root.right = new TreeNode(14);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(8);
root.right.left = new TreeNode(12);
root.right.right = new TreeNode(16);
TreeNode convert = Convert(root);
int a = 1;
}
static TreeNode pre = null;
static TreeNode root = null;
public static TreeNode Convert(TreeNode pRootOfTree) {
if (pRootOfTree == null) {
return null;
}
//左树
Convert(pRootOfTree.left);
if (root == null) {
root = pRootOfTree;
}
//与中序遍历的前一个结点进行关联
if (pre != null) {
pRootOfTree.left = pre;
pre.right = pRootOfTree;
}
//保留中序遍历的前一个结点
pre = pRootOfTree;
//右树
Convert(pRootOfTree.right);
return root;
}
}
参考线索二叉树
https://www.cnblogs.com/zhuyf87/archive/2012/11/03/2752722.html