对于一般二叉树的转变成单(双)链表来说,只需要 后续遍历就可以!
/**
* 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:
void flatten(TreeNode* root) {
if(!root) return;
flatten(root->left);
flatten(root->right);
//这里任然采用递归
if(!root->left) return;
TreeNode *pNode = root->left; //设置工作节点
while(!pNode->right) //得到左子树生成的链表的最右端结点
pNode = pNode->right;
pNode->right = root->right;
root->right = root->left;
root->left = NULL; //NULL root root->left pNode->right root->right
}
};
二叉树转换为双向链表,但是有点没看懂 pair
#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) return;
output_tree(r->left);
cout << r->val << " ";
output_tree(r->right);
}
void output_list(TreeNode *head)
{
TreeNode *ph = head;
for (; ph; ph = ph->right) cout << ph->val << " ";
cout << endl;
}
int main()
{
TreeNode n4(4), n8(8), n6(6, &n4, &n8), n12(12), n16(16), n14(14, &n12, &n16), n10(10, &n6, &n14);
output_tree(&n10);
cout << endl;
TreeNode *head = convert2list(&n10);
output_list(head);
return 0;
}
#include <stdio.h>
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode (int x):val(x),left(NULL),right(NULL){}
};
int flatten(TreeNode* root) {
if(root =NULL)
return -1;
flatten(root->left);
flatten(root->right);
if(!root->left)
return ;
TreeNode *pNode = root->left; //将左子树生成的链表插入到root与root->right中间
while(!pNode->right) //得到左子树生成的链表的最右端结点
pNode = pNode->right;
pNode->right = root->right;
root->right = root->left;
root->left = NULL; //NULL root root->left pNode->right root->right
return ;
}
int main()
{
TreeNode a(1);
TreeNode b(2);
TreeNode c(5);
TreeNode d(3);
TreeNode e(4);
TreeNode f(6);
a.left =&b;
a.right =&c;
b.left =&d;
b.right =&e;
c.right = &f;
//preorder(&a,0);
flatten(&a);
TreeNode *head = &a;
printf("%d",head -> val);
printf("/n");
/*
while(head)
{
printf("%d\n",head->val);
head = head ->right;
}*/
return 0;
}