您的位置:首页 > 其它

LeetCode Flatten Binary Tree to Linked List

2015-02-08 15:21 288 查看
题目

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;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: