Description
Given a binary tree, flatten it to a linked list in-place.
Example
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
Solution 1(C++)
class Solution {
public:
void flatten(TreeNode* root) {
if (!root) return;
if (root->left) flatten(root->left);
if (root->right) flatten(root->right);
TreeNode *tmp = root->right;
root->right = root->left;
root->left = NULL;
while (root->right) root = root->right;
root->right = tmp;
}
};
Solution 2(C++)
class Solution {
public:
void flatten(TreeNode* root) {
TreeNode *cur = root;
while (cur) {
if (cur->left) {
TreeNode *p = cur->left;
while (p->right) p = p->right;
p->right = cur->right;
cur->right = cur->left;
cur->left = NULL;
}
cur = cur->right;
}
}
};
Solution 3(C++)
class Solution {
public:
void flatten(TreeNode* root) {
if (!root) return;
stack<TreeNode*> stk;
stk.push(root);
while (!stk.empty()) {
TreeNode *t = stk.top(); stk.pop();
if (t->left) {
TreeNode *r = t->left;
while (r->right) r = r->right;
r->right = t->right;
t->right = t->left;
t->left = NULL;
}
if (t->right) stk.push(t->right);
}
}
};
算法分析
解法一
递归版本。递归二叉树中的所有左右子节点,然后将左子树所形成的链表插入到root和root->right之间,过程为,找到根节点的左节点,找到左链表的最后一个节点,将根节点的右子树连接到左链表的最后一个节点只上,之后将根节点的左链表连接到根节点的右节点位置上,之后将根节点的左节点赋值为空指针。
解法二
非迭代版本的实现,这个方法是从根节点开始出发,先检测其左子结点是否存在,如存在则将根节点和其右子节点断开,将左子结点及其后面所有结构一起连到原右子节点的位置,把原右子节点连到元左子结点最后面的右子节点之后。
解法三
前序迭代解法。利用栈辅助完成。