题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。
要求不能创建任何新的结点,只能调整树中结点指针的指向。
注意:
- 需要返回双向链表最左侧的节点。
例如,输入下图中左边的二叉搜索树,则输出右边的排序双向链表。
问题分析
先判断根节点如果为空,那么返回NULL。然后调用递归函数helper,此函数传入的参数是二叉搜索树的根节点,返回的是一个pair,pair里面是该二叉搜索树转为双向链表后的头节点和尾节点。所以返回头节点即可。在helper函数中:我们先判断如果根节点没有左孩子和右孩子,那么返回的pair是{root, root};如果根节点有左孩子和右孩子,那么我们分别用左孩子调用helper函数和用右孩子调用helper函数,然后我们用左孩子返回的pair的尾节点连接上root,用右孩子返回的pair的头节点连接上root,那么返回的pair是{aleft.first, aright.second};如果根节点只有左孩子,那么我们用左孩子调用helper函数,然后用左孩子返回的pair的尾节点连接上root,那么返回的pair是{aleft.first, root};如果根节点只有右孩子,那么我们用右孩子调用helper函数,然后用右孩子返回的pair的头节点连接上root,那么返回的pair是{root, aright.second}。
代码实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* convert(TreeNode* root) {
if(!root)
return NULL;
auto a = helper(root);
return a.first;
}
pair<TreeNode*, TreeNode*> helper(TreeNode* root){
if(!root->left && !root->right)
return {root, root};
else if(root->left && root->right){
auto aleft = helper(root->left);
auto aright = helper(root->right);
aleft.second->right = root;
root->left = aleft.second;
root->right = aright.first;
aright.first->left = root;
return {aleft.first, aright.second};
}
else if(root->left){
auto aleft = helper(root->left);
aleft.second->right = root;
root->left = aleft.second;
return {aleft.first, root};
}
else if(root->right){
auto aright = helper(root->right);
root->right = aright.first;
aright.first->left = root;
return {root, aright.second};
}
}
};