Problem with trees
This is a general recursive approach to resolve problems on binary trees by using a predefined type of algorithm
Factorizable
It is based on Divide et Impera.
cpp
factorizable(Node u)
if (u == NULL): //Test if tree is empty
// Direct Solution
// DIVIDE ET IMPERA
else:
left_res = factorizable(u->left);
right_res = factorizable(u->right);
//evaluate some more more conditions
// COMBINE
return recombine(left_res, right_res);factorizable(Node u)
if (u == NULL): //Test if tree is empty
// Direct Solution
// DIVIDE ET IMPERA
else:
left_res = factorizable(u->left);
right_res = factorizable(u->right);
//evaluate some more more conditions
// COMBINE
return recombine(left_res, right_res);python
factorizable(Node u)
if (u == NULL): #Test if tree is empty
# Direct Solution
# DIVIDE ET IMPERA
else:
left_res = factorizable(u.left);
right_res = factorizable(u.right);
#evaluate some more more conditions
# COMBINE
return recombine(left_res, right_res);factorizable(Node u)
if (u == NULL): #Test if tree is empty
# Direct Solution
# DIVIDE ET IMPERA
else:
left_res = factorizable(u.left);
right_res = factorizable(u.right);
#evaluate some more more conditions
# COMBINE
return recombine(left_res, right_res);php
function factorizable(Node $u){
if ($u == NULL){ #Test if tree is empty
// Direct Solution
} # DIVIDE ET IMPERA
else{
$left_res = factorizable($u->left);
$right_res = factorizable($u->right);
//evaluate some more more conditions
// COMBINE
return recombine($left_res, $right_res);
}
}function factorizable(Node $u){
if ($u == NULL){ #Test if tree is empty
// Direct Solution
} # DIVIDE ET IMPERA
else{
$left_res = factorizable($u->left);
$right_res = factorizable($u->right);
//evaluate some more more conditions
// COMBINE
return recombine($left_res, $right_res);
}
}Complexity demonstration
Since the algorithm covers all the nodes, we have
We can then rewrite the recursive complexity formula as
Where
is the time to cover the left subtree's nodes is the time to cover the right subtree' s nodes to exclude the root and the left subtree
Since we do not have a clue whether the tree is balanced or not, we cannot use the master theorem to get the total time complexity.
- Knowing that the tree is balanced means that
, which would change the formula in or
We use the substitution method:
- Hypothesis: The time is a generic linear combination
- Proceed by induction to find
and - Base Case:
by definition of - Inductive Hypothesis: We assume that
so we can rewrite - Inductive Step: Demonstrate it for
- Base Case:
Since
Now, we want to demonstrate that
Final Time Complexity:
- Every node is iterated through then we have
- If base case and recombine have