题目
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
将一颗二叉树转换为链,要求原地进行。
可以观察到,需要的输出结果实际就是原树的先序遍历序列。
先序遍历,将新发现的节点连接到上一个节点的左节点,则:
1、如果新发现的节点是上一个节点的左子节点,则原本的连接关系不需要修改。
2、否则,上一个节点必然是叶节点,将新发现的节点连接为上一个节点的左子节点,
由于上一个节点已经探测结束,所以将新发现的节点连接在其左子树上不会影响后续的遍历。
最后递归扫描修改后的树的左子节点,将左节点连接为右子节点,将左子节点设为空即可。
代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void to_left(TreeNode* root,TreeNode *&last) //当前位置,上一位置;先序遍历,将后一节点连在前一节点左子树上。
{
if(root==NULL)
return;
if(last!=NULL)
last->left=root;
last=root; //修改上一位置
to_left(root->left,last); //递归
to_left(root->right,last);
}
void flatten(TreeNode *root) {
TreeNode* last=NULL;
to_left(root,last);
while(root!=NULL) //递归将左子树移位右子树,清空右子树连接
{
root->right=root->left;
root->left=NULL;
root=root->right;
}
}
};
本文介绍了如何将二叉树转换为链表,通过原地进行先序遍历来实现这一过程。具体步骤包括确定当前节点与上一节点的关系,并在遍历中调整节点连接。
833

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



