#include <iostream>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int v = 0, TreeNode *l = nullptr, TreeNode *r = nullptr) : val(v), left(l), right(r) {}
};
pair<TreeNode *, TreeNode *> convert(TreeNode *root)
{
if (!root) return make_pair(nullptr, nullptr);
TreeNode *left = nullptr, *right = nullptr;
auto pl = convert(root->left);
auto pr = convert(root->right);
if (pl.second)
{
root->left = pl.second;
pl.second->right = root;
left = pl.first;
}
else
{
root->left = nullptr;
left = root;
}
if (pr.first)
{
root->right = pr.first;
pr.first->left = root;
right = pr.second;
}
else
{
root->right = nullptr;
right = root;
}
return make_pair(left, right);
}
TreeNode *convert2list(TreeNode *root)
{
return convert(root).first;
}
void output_tree(TreeNode *r)
{
if (!r) re
二叉树转换为双向链表(后序遍历)
最新推荐文章于 2020-11-24 11:00:38 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)