Given a N-ary tree construct a new binary tree as follows:
Pre-order: pre-order traversal in the original tree is identical to pre-order traversal in the Knuth-transformed tree.
Post-order: post-order traversal in the Knuth trasnform tree, requires three steps: left, root, right
LCRS_tree class
template <typename Type>
class LCRS_tree {
private:
Type element;
LCRS_tree *first_child_tree;
LCRS_tree *next_sibling_tree;
public:
LCRS_tree();
LCRS_tree *first_child();
LCRS_tree *next_sibling();
};
degree()
template<typename Type>
int LCRS_tree<Type>::degree() const {
int count = 0;
for (LCRS_tree *ptr = first_child();
ptr != nullptr;
ptr = ptr->next_sibling()) {
++ count;
}
return count;
}
is_leaf()
template<typename Type>
bool LCRS_tree<Type>::is_leaf() const {
return (first_child() == nullptr);
}
size()
template<typename Type>
int LCRS_tree<Type>::size() const {
return 1 +
(first_child() == nullptr ? 0 : first_child()->size()) +
(next_sibling() == nullptr ? 0 : next_sibling()->size());
}
height()
template<typename Type>
int LCRS_tree<Type>::height() const {
int h = 0;
for (LCRS_tree *ptr = first_child();
ptr != nullptr;
ptr = ptr->next_sibling()) {
h = std::max(h, 1 + ptr->height());
}
return h;
}
In [ ]: