AcWing 49. 二叉搜索树与双向链表
原题链接
中等
作者:
adamXu
,
2020-09-28 08:39:21
,
所有人可见
,
阅读 383
/**
* 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 x = dfs(root);
return x.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};
}
if(root->right){
auto rside = dfs(root->right);
rside.first->left = root,root->right = rside.first;
return {root,rside.second};
}
}
};