AcWing 49. 二叉搜索树与双向链表
原题链接
中等
作者:
Baymax0211
,
2019-04-13 16:18:02
,
所有人可见
,
阅读 938
算法1
(递归)
- 每次返回一个pair,分别表示已经连接双向链表的左边的节点与右边的节点
- 有几种特判情况
- 左右节点均不存在
- 左右节点均存在,两边进行连接
- 左节点存在,root与左边的链表进行连接
- 右节点存在,root与右边的链表进行连接
C++ 代码
//代码参考yxc
/**
* 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 nullptr;
auto side = dfs(root);
return side.first;
}
pair<TreeNode* ,TreeNode*> dfs(TreeNode* root){
if(!root->left&&!root->right)return {root,root};
if(root->left && root->right) {
auto lside =dfs(root->left),rside = dfs(root->right);
lside.second->right = root,root->left = lside.second;
rside.first->left = root,root->right = rside.first;
return {lside.first,rside.second};
}
if(root->left){
auto lside =dfs(root->left);
lside.second->right = root,root->left = lside.second;
return {lside.first,root};
}else
{
auto rside = dfs(root->right);
rside.first->left = root,root->right = rside.first;
return {root,rside.second};
}
}
};