难度:中等
给定一个二叉树,原地将它展开为一个单链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
题目分析:
直接前序遍历非递归版,然后将所有节点存储起来,最后使用右指针链接起来,左指针都置null(空间复杂度偏高)
参考代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void flatten(TreeNode* root) {
if(root == NULL)
return;
TreeNode* pMove = root;
stack<TreeNode*> node_stack;
vector<TreeNode*> node_data;
while(pMove || !node_stack.empty())
{
while(pMove)
{
node_data.push_back(pMove);
node_stack.push(pMove);
pMove = pMove->left;
}
if(!node_stack.empty())
{
pMove = node_stack.top();
node_stack.pop();
pMove = pMove->right;
}
}
for(int i = 0; i < node_data.size(); i++)
{
node_data[i]->left = nullptr;
if(i+1 < node_data.size())
node_data[i]->right = node_data[i+1];
}
}
};
前面使用了其他数据结构,并不满足题目要求,下面分别用前序遍历和后序遍历来实现,理解可以看下面视频。
B站:https://www.bilibili.com/video/BV1rJ41117G1?from=search&seid=13649737786739771510
参考代码:(前序遍历)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void flatten(TreeNode* root) {
if(root == NULL)
return;
//先把当前节点的右子树记录下来
TreeNode* temp_right = root->right;
//把左子树放到原来右子树的位置
root->right = root->left;
//把左子树清空
root->left = NULL;
TreeNode* pMove = root;
//遍历到当前右子树的最后一个节点
while(pMove->right)
{
pMove = pMove->right;
}
//把原右子树连接到现右子树上
pMove->right = temp_right;
flatten(root->right);
}
};
参考代码:(后序遍历)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
//这里的后序遍历是右 左 根
class Solution {
public:
TreeNode* last_node = NULL;
void flatten(TreeNode* root) {
if(root == NULL)
return;
flatten(root->right);
flatten(root->left);
//从第二次开始当前节点的右子树指向前一个节点,左子树清空,移动前一个节点
if(last_node)
{
root->right = last_node;
root->left = NULL;
}
last_node = root;
}
};