[InterviewBit] Flatten Binary Tree to Linked List

Flatten Binary Tree to Linked List

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
TreeNode* helper(TreeNode* A) {
TreeNode* res = A;
if(A->left == NULL and A->right == NULL) return res;
if(A->left == NULL and A->right != NULL) return helper(res->right);
if(A->left != NULL and A->right == NULL) {
swap(res->left, res->right);
return helper(res->right);
}
TreeNode* l = A->left;
TreeNode* r = A->right;
res->right = res->left = NULL;
res->right = l;
TreeNode* leftTail = helper(l);
leftTail->right = r;
return helper(r);
}
TreeNode* Solution::flatten(TreeNode* A) {
helper(A);
return A;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/01/PS/interviewbit/flatten-binary-tree-to-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.