二叉搜索树与双向链表
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
遇树不决就递归
/*
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)
{
if(pRootOfTree == NULL) return NULL;
if(pRootOfTree->left == NULL && pRootOfTree->right == NULL) return pRootOfTree;
if(pRootOfTree->left == NULL) {
TreeNode * temp = Convert(pRootOfTree->right);
pRootOfTree->right = temp;
temp->left = pRootOfTree;
return pRootOfTree;}
if(pRootOfTree->right == NULL) {
TreeNode * temp = Convert(pRootOfTree->left);
TreeNode * tmp = temp;
while(temp->right) {
temp = temp->right;
}
temp->right = pRootOfTree;
pRootOfTree->left = temp;
return tmp;
}
TreeNode * temp = Convert(pRootOfTree->left);
TreeNode * tmp = temp;
while(temp->right) {
temp = temp->right;
}
temp->right = pRootOfTree;
pRootOfTree->left = temp;
temp = Convert(pRootOfTree->right);
pRootOfTree->right = temp;
temp->left = pRootOfTree;
return tmp;
}
};
还没有评论,来说两句吧...