[AlgoExpert] Find Successor

Find Successor

  • 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
using namespace std;

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

BinaryTree(int value) { this->value = value; }
};
void helper(BinaryTree* node, BinaryTree* target, BinaryTree** res, bool& search) {
if(!node or *res != nullptr) return;
helper(node->left, target, res, search);
if(search) {*res = node; search = false;}
if(target == node) search = true;
helper(node->right, target, res, search);

}
BinaryTree *findSuccessor(BinaryTree *tree, BinaryTree *node) {
BinaryTree* res = nullptr;
bool search = false;
helper(tree, node, &res, search);
return res;
}

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