二叉树(数组表示)

Posted chengmf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树(数组表示)相关的知识,希望对你有一定的参考价值。

.h 文件:

#pragma once

class Tree
{
public:
    Tree(int size, int* pRoot);
    ~Tree();
    int* SearchNode(int nodeIndex);  //查找
    bool AddNode(int nodeIndex, int direction, int* pNode);//添加
    bool DeleteNode(int nodeIndex, int* pNode);//删除
    void TreeTraverse();//遍历
private:
    int* m_pTree;  
    int m_Size;
};

.cpp 文件:

#include<iostream>
#include "Tree.h"
using namespace std;

Tree::Tree(int size, int* pRoot)
{
    m_Size = size;
    m_pTree = new int[size];

    for (int i = 0; i < size; ++i)
    {
        m_pTree[i] = 0;
    }

    m_pTree[0] = *pRoot;
}

Tree::~Tree()
{
    delete[] m_pTree;
    m_pTree = nullptr;
}

int* Tree::SearchNode(int nodeIndex)
{
    if (nodeIndex < 0 || nodeIndex >= m_Size)return nullptr;
    if (m_pTree[nodeIndex] == 0)return nullptr;

    return &m_pTree[nodeIndex];
}

bool Tree::AddNode(int nodeIndex, int direction, int* pNode)
{
    if (nodeIndex < 0 || nodeIndex >= m_Size)return false;  //判断父节点索引是否正确
    if (m_pTree[nodeIndex] == 0)return false;  //判断父节点是否为空

    if (direction == 0) //左
    {
        if (nodeIndex * 2 + 1 >= m_Size)return false; //判断左孩子索引是否正确
        if (m_pTree[nodeIndex * 2 + 1] != 0)return false; //左孩子不为0说明已经有数据

        m_pTree[nodeIndex * 2 + 1] = *pNode;
    }
    if (direction == 1)//右
    {
        if (nodeIndex * 2 + 2 >= m_Size)return false;
        if (m_pTree[nodeIndex * 2 + 2] != 0)return false;

        m_pTree[nodeIndex * 2 + 2] = *pNode;
    }
    return true;
}

bool Tree::DeleteNode(int nodeIndex, int* pNode)
{
    if (nodeIndex < 0 || nodeIndex >= m_Size)return false;
    if (m_pTree[nodeIndex] == 0)return false;

    *pNode = m_pTree[nodeIndex];
    m_pTree[nodeIndex] = 0;

    return true;
}

void Tree::TreeTraverse()
{
    for (int i = 0; i < m_Size; ++i)
    {
        cout << m_pTree[i] << " ";
    }
}

测试代码:

#include<iostream>
#include"Tree.h"
using namespace std;

int main()
{
    int root = 3;
    Tree* pt = new Tree(10,&root);
    int node1 = 5;
    int node2 = 8;
    int node3 = 2;
    int node4 = 6;
    int node5 = 9;
    int node6 = 7;

    pt->AddNode(0, 0, &node1);
    pt->AddNode(0, 1, &node2);

    pt->AddNode(1, 0, &node3);
    pt->AddNode(1, 1, &node4);

    pt->AddNode(2, 0, &node5);
    pt->AddNode(2, 1, &node6);
    
    int node = 0;
    pt->DeleteNode(6, &node);
    cout << node << endl;

    pt->TreeTraverse();
    cout << endl;

    int *p = pt->SearchNode(2);
    cout << *p << endl;

    delete pt;

    return 0;
}

以上是关于二叉树(数组表示)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 0919. 完全二叉树插入器:完全二叉树的数组表示

NC41 最长无重复子数组/NC133链表的奇偶重排/NC116把数字翻译成字符串/NC135 股票交易的最大收益/NC126换钱的最少货币数/NC45实现二叉树先序,中序和后序遍历(递归)(代码片段

二叉树(数组表示)

二叉树的遍历--递归实现与非递归实现

同一棵二叉树?(二叉树)

构造二叉树