Skip to content

Instantly share code, notes, and snippets.

@danielSanchezQ
Created November 14, 2017 19:04
Show Gist options
  • Save danielSanchezQ/4280e99ee0118c96ea793b264a971870 to your computer and use it in GitHub Desktop.
Save danielSanchezQ/4280e99ee0118c96ea793b264a971870 to your computer and use it in GitHub Desktop.
// bInarytree.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <algorithm>
class BinaryTree
{
private:
int m_val;
BinaryTree* m_left;
BinaryTree* m_right;
public:
BinaryTree(int val)
{
m_val = val;
}
BinaryTree(int val, BinaryTree* l, BinaryTree* r)
{
m_val = val;
m_left = l;
m_right = r;
}
void setVal(int val)
{
m_val = val;
}
int getVal() { return m_val; }
void printVal()
{
std::cout << m_val;
}
void printPreAll()
{
printVal();
if (m_left != nullptr) m_left ->printPreAll();
if (m_right != nullptr) m_right->printPreAll();
}
void printPostAll()
{
if (m_left != nullptr) m_left ->printPostAll();
if (m_right != nullptr) m_right->printPostAll();
printVal();
}
void printInAll()
{
if (m_left != nullptr) m_left->printInAll();
printVal();
if (m_right != nullptr) m_right->printInAll();
}
void setChild(int val, bool atLeft = true)
{
if (atLeft)
{
if (m_left != nullptr) m_left = new BinaryTree(val);
else m_left->setVal(val);
}
else
{
if (m_right != nullptr) m_right = new BinaryTree(val);
else m_right->setVal(val);
}
}
int height()
{
if (m_left == nullptr && m_right == nullptr) return 1;
int l_max, r_max;
if (m_left != nullptr) l_max = 1 + m_left->height();
else l_max = 0;
if (m_right != nullptr) r_max = 1 + m_right->height();
else r_max = 0;
return std::max(l_max, r_max);
}
int size()
{
int l_size, r_size;
if (m_left != nullptr) l_size = m_left->size();
else l_size = 0;
if (m_right != nullptr) r_size = m_right->size();
else r_size = 0;
return 1 + l_size + r_size;
}
BinaryTree* search(int val)
{
if (m_val == val) return this;
else if (m_left == nullptr && m_right == nullptr) return nullptr;
BinaryTree* ret;
if (m_left != nullptr)
{
ret = m_left->search(val);
if (ret != nullptr) return ret;
}
return m_right->search(val);
}
};
int main()
{
BinaryTree* parent = new BinaryTree
(
1,
new BinaryTree(2),
new BinaryTree
(
3,
new BinaryTree
(
5,
new BinaryTree(8),
new BinaryTree(9)
),
new BinaryTree
(
6,
new BinaryTree(10),
nullptr
)
)
);
parent->printPreAll();
std::cout << "\n";
parent->printPostAll();
std::cout << "\n";
parent->printInAll();
std::cout << "\n";
std::cout << parent->height();
std::cout << "\n";
std::cout << parent->size();
std::cout << "\n";
BinaryTree* res = parent->search(10);
std::cout << res->getVal();
std::getchar();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment