原题链接

将递归函数的返回类型设定为一个pair<T,T>,表示递归的链表中的最左侧节点和最右侧节点,之后返回最左侧节点即为我们的答案。

代码
/**
* 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* ans;
TreeNode* convert(TreeNode* root) {
if(!root) return NULL;
auto dummy=dfs(root);
return dummy.first;
}
pair<TreeNode*,TreeNode*> dfs(TreeNode *root)
{
if(!root->left && !root->right) return {root,root};
if(root->left && root->right)
{
auto t1=dfs(root->left);
t1.second->right=root,root->left=t1.second;
auto t2=dfs(root->right);
t2.first->left=root,root->right=t2.first;
return {t1.first,t2.second};
}
if(root->left && !root->right)
{
auto t=dfs(root->left);
t.second->right=root,root->left=t.second;
return {t.first,root};
}
if(!root->left && root->right)
{
auto t=dfs(root->right);
t.first->left=root,root->right=t.first;
return {root,t.second};
}
}
};
该代码实现了一个递归函数,用于将二叉树转换并返回一个pair,包含链表中最左侧和最右侧的节点。通过深度优先搜索(DFS),先处理左子树,然后右子树,最后连接节点以形成链表。返回的最左侧节点即为所求解。

被折叠的 条评论
为什么被折叠?



