[AlgoExpert] Compare Leaf Traversal

Compare Leaf Traversal

  • Time : O(n + m)
  • Space : O(leaf(n) + leaf(m))
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
using namespace std;

// This is an input class. Do not edit.

class BinaryTree {
public:
int value;
BinaryTree *left = nullptr;
BinaryTree *right = nullptr;

BinaryTree(int value) { this->value = value; }
};

void travel(vector<int>& res, BinaryTree* tree) {
if(tree->left == nullptr and tree->right == nullptr) res.push_back(tree->value);
else {
if(tree->left) travel(res, tree->left);
if(tree->right) travel(res, tree->right);
}
}

bool compareLeafTraversal(BinaryTree *tree1, BinaryTree *tree2) {
if(tree1 == nullptr) return tree2 == nullptr;
if(tree2 == nullptr) return tree1 == nullptr;
vector<int> leaf1, leaf2;
travel(leaf1, tree1);
travel(leaf2, tree2);
return leaf1 == leaf2;
}

  • Time : O(n + m)
  • Space : O(leaf(n))
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
32
33
34
35
36
37
38
39
40
41
42
43
using namespace std;

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

BinaryTree(int value) { this->value = value; }
};

void travel1(vector<int>& res, BinaryTree* tree) {
if(tree->left == nullptr and tree->right == nullptr) res.push_back(tree->value);
else {
if(tree->left) travel1(res, tree->left);
if(tree->right) travel1(res, tree->right);
}
}

bool travel2(vector<int>& res, BinaryTree* tree) {
if(tree->left == nullptr and tree->right == nullptr) {
if(res.empty() or tree->value != res.back()) return false;
res.pop_back();
return true;
} else {
if(tree->right) {
if(!travel2(res, tree->right)) return false;
}
if(tree->left) {
if(!travel2(res, tree->left)) return false;
}
return true;
}
}

bool compareLeafTraversal(BinaryTree *tree1, BinaryTree *tree2) {
if(tree1 == nullptr) return tree2 == nullptr;
if(tree2 == nullptr) return tree1 == nullptr;
vector<int> leaf;
travel1(leaf, tree1);
return travel2(leaf, tree2);
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/compare-leaf-traversal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.