114. Flatten Binary Tree to Linked List

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
void flatten(TreeNode* root) {
if(!root) return;

flatten(root->left);
flatten(root->right);

TreeNode * temp = root->right;
root->right = root->left;
root->left = nullptr;
TreeNode *p = root;
while(p->right) p=p->right;
p->right = temp;

}
};

analysis

  • time complexity O(n)
  • space complexity O(1)