数组实现二叉树

7 篇文章 0 订阅

下面我们构造一个简单的二叉树,主要看清构造二叉树的思路;
解释一下,这里我们将二叉树的左节点和右边节点分别用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();
}

参考网站:(http://www.imooc.com/learn/673

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值