题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
分析
从根节点开始调整,把最左最右节点的值返回,使用引用作为传递
代码实现
TreeNode* Convert(TreeNode* root)
{
if(root==NULL)return NULL;
TreeNode* start;
TreeNode* end;
Convert( root, start, end);
return start;
}
void Convert(TreeNode* root, TreeNode* & start, TreeNode* & end)
{
if (root->left == NULL && root->right == NULL ) {
start=root;
end=root;
return;
}
TreeNode* start_left=NULL;
TreeNode* end_left=NULL;
if (root->left) {
Convert(root->left, start_left, end_left);
end_left->right = root;
root->left = end_left;
}
TreeNode* start_right=NULL;
TreeNode* end_right=NULL;
if (root->right) {
Convert(root->right, start_right, end_right);
start_right->left = root;
root->right = start_right;
}
if(start_left)
start = start_left;
else
start = root;
if(end_right)
end = end_right;
else
end = root;
}