#Binary Tree Implementation
5 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.
This is the class for the Node:
#include <datenstrukturen/treenode.hpp>
#include <vector>
#include <iostream>
namespace Datenstrukturen{
TreeNode::TreeNode(int data){
data_ = data;
}
int TreeNode::get_data(){
return data_;
}
void TreeNode::set_data(int data){
data_ = data;
}
std::shared_ptr<TreeNode> TreeNode::get_left_child() {
return left_child;
}
std::shared_ptr<TreeNode> TreeNode::get_right_child() {
return right_child;
}
void TreeNode::set_left_child(int data) {
// if the child does not exist yet
if (!left_child){
left_child = std::make_shared<TreeNode>(data);
}
else{
// set data for existing child
left_child->set_data(data);
}
}
void TreeNode::set_left_child(std::shared_ptr<TreeNode> node, int data){
if (!left_child){
left_child = std::make_shared<TreeNode>(data);
parent = node;
std::cout<< parent.lock()->get_data()<<std::endl;
}
else{
// set data for existing child
left_child->set_data(data);
}
}
void TreeNode::set_right_child(int data) {
// the same things as for set_left_child
if (!right_child){
right_child = std::make_shared<TreeNode>(data);
}
else{
right_child->set_data(data);
}
}
void TreeNode::set_right_child(std::shared_ptr<TreeNode> par, int data){
if (!right_child){
right_child = std::make_shared<TreeNode>(data);
parent = par;
}
else{
// set data for existing child
right_child->set_data(data);
}
}
// Removes the left child (if it exists)
void TreeNode::remove_left_child() {
// all following children are also deleted
if (left_child)
left_child.reset();
}
// Removes the right child (if it exists)
void TreeNode::remove_right_child(){
// reset pointer {
// all following are also deleted
if (right_child)
right_child.reset();
}
std::shared_ptr<TreeNode> TreeNode::get_parent(){
return parent.lock();
}
}
This question thread is being automatically closed. If your question is not answered feel free to bump the post or re-ask. Take a look at !howto ask for tips on improving your question.