题目:
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
思路:DFS,返回后左右子树已经flatten完毕,这个时候只有要找到左子树的的叶子节点,把右子树接过去,然后整体作为root的右子树即可。
class Solution {
public:
void flatten(TreeNode *root) {
if (root == nullptr) return;
flatten(root->left);
flatten(root->right);
if (root->left == nullptr) return;
TreeNode* tail = root->left;
while (tail->right != nullptr) tail = tail->right;
tail->right = root->right;
root->right = root->left;
root->left = nullptr;
}
};
总结:复杂度为O(2^n).