下面我们构造一个简单的二叉树,主要看清构造二叉树的思路;
解释一下,这里我们将二叉树的左节点和右边节点分别用0和1表示,同时将不存在的节点的值用0来表示.
binaryTree.h
class BinaryTree{
public:
BinaryTree(int nSize, int *root);
bool addTreeNode(int pos, int* parent, int direct, int *node);
bool delTreeNode(int i);
void traverseTree();
~BinaryTree();
friend bool cimi(int x);
private:
int *m_Ptree;
int size_tree;
};
bool cimi(int x){
return (x&(x - 1)) ? true : false;
}
createBinaryTree.cpp
#include <iostream>
#include <cstdlib>
#include <cmath>
#include "binaryTree.h"
using namespace std;
BinaryTree::BinaryTree(int size, int *root){
m_Ptree = new int[size];
for (int i = 0; i < size; i++){
m_Ptree[i] = 0;
}
m_Ptree[0] = *root;
size_tree = size;
}
bool BinaryTree::delTreeNode(int i){
if (i < 0 || i >= size_tree){
return false;
}
if (m_Ptree[i] == 0){
return false;
}
m_Ptree[i] = 0;
}
bool BinaryTree::addTreeNode(int pos, int *parent,int direction,int *node){
if (direction == 0){
if (pos * 2 + 1 < 0 || pos * 2 + 1 >=size_tree){
cout << "左边超出" << endl;
return false;
}
if (m_Ptree[pos * 2 + 1] != 0){
cout << "左孩子已经有值" << endl;
return false;
}
cout << "第" << pos * 2 + 1 << "个子节点" << endl;
m_Ptree[pos * 2 + 1] = *node;
}
else{
if (pos * 2 + 2 < 0 || pos * 2 + 2 >= size_tree){
return false;
}
if (m_Ptree[pos * 2 + 2] != 0){
return false;
}
cout << "第" << pos * 2 + 2 << "个子节点" << endl;
m_Ptree[pos * 2 + 2] = *node;
}
}
void BinaryTree::traverseTree(){
for (int i = 0; i < size_tree; i++){
cout << m_Ptree[i] << " ";
}
cout << endl;
}
BinaryTree::~BinaryTree(){
delete[] m_Ptree;
m_Ptree = NULL;
}
int main(){
int root = 10;
BinaryTree bTree(7, &root);
int node1 = 7;
int node2 = 8;
bTree.addTreeNode(0, &root, 0, &node1);
bTree.addTreeNode(0, &root, 1, &node2);
int node3 = 6;
int node4 = 10;
bTree.addTreeNode(1, &node1, 0, &node3);
bTree.addTreeNode(1, &node1, 1, &node4);
int node5 = 100;
int node6 = 70;
bTree.addTreeNode(2, &node2, 0, &node5);
bTree.addTreeNode(2, &node2, 1, &node6);
bTree.traverseTree();
bTree.delTreeNode(6);
bTree.traverseTree();
}