您的位置:首页 > 其它

LeetCode题解: Flatten Binary Tree to Linked List

2013-11-17 07:42 507 查看

Flatten Binary Tree to Linked List

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

思路:

按preorder顺序访问树,使用迭代的方式进行。这样迭代过程中下一个结点就是当前结点的右子树,而设置当前结点的左子树为空,最后形成目标链表。

题解:

/**
* 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 == nullptr)
return;

list<TreeNode*> q;
q.push_back(root);
while(! q.empty())
{
TreeNode* t  = q.front();
q.pop_front();

if (t->right) q.push_front(t->right);
if (t->left) q.push_front(t->left);

t->left = nullptr;
t->right = q.empty() ? nullptr : q.front();
}

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