[AlgoExpert] Flatten Binary Tree

Flatten Binary Tree

  • 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
31
#include <vector>
using namespace std;

// This is the class of the input root. Do not edit it.
class BinaryTree {
public:
int value;
BinaryTree *left = nullptr;
BinaryTree *right = nullptr;

BinaryTree(int value);
};
BinaryTree* prv;
void travel(BinaryTree* node) {
if(!node) return;
travel(node->left);

prv->right = node;
node->left = prv;
prv = node;
travel(node->right);
}

BinaryTree *flattenBinaryTree(BinaryTree *root) {
prv = new BinaryTree(-1);
BinaryTree& dummy = *prv;
travel(root);
dummy.right->left = nullptr;
return dummy.right;
}

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