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
思路:先做一次先序遍历,把结点存储在一个向量中,最后把向量中的每个元素p(i)作为它上个元素p(i-1)的右结点,且p(i-1)的左结点为空。除了最后那个元素,其左右结点都为空。
/**
* 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 flatten(TreeNode *root) {
if(root)
{
path(root);
int i;
TreeNode* t = root;
root->left = NULL;
for(i=1; i<v.size(); ++i)
{
t->right = v[i];
t = t->right;
t->left = NULL;
}
t->right = NULL;
}
}
void path(TreeNode *root)//递归,先序遍历
{
if(root)
{
v.push_back(root);
if(root->left)
path(root->left);
if(root->right)
path(root->right);
}
}
private:
vector<TreeNode*> v;//存储先序遍历的结果
};
本文介绍了一种将二叉树结构通过先序遍历的方式转换为链表的方法。该方法首先进行先序遍历并将节点保存到向量中,然后依次将向量中的每个节点设置为其前一个节点的右子节点,并确保所有左子节点为空。
294

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



