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
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
这道题是按照前序遍历的顺序拉平二叉树,题目难度为Medium。
由于题目要求in-place,而传统前序遍历二叉树的方法或递归或借助栈,都不符合要求,因此要想其他的解决办法。
针对任意节点,如果它没有右子树,直接把它的左子树移到右子树即可;如果没有左子树,此节点不需要处理,直接处理下一个节点;如果左子树和右子树都存在,为了达到前序遍历的顺序,我们需要把它的整个右子树移动到左子树前序遍历最后一个节点之后,这样当前节点就变成了没有右子树的情况了,可以按照第一种情况进行处理。具体代码:
class Solution {
public:
void flatten(TreeNode* root) {
while(root) {
if(root->left) {
if(root->right) {
TreeNode* node = root->left;
while(node->right)
node = node->right;
node->right = root->right;
}
root->right = root->left;
root->left = NULL;
}
root = root->right;
}
}
};
虽然这样处理能够达到in-place的前序遍历,但它的时间复杂度要比传统的方法高。