二叉树的C++实现

数据结构与二叉树类的定义

我采用链式存储结构来表示二叉树,每一个二叉树节点包含树节点的值、树的左孩子指针、树的右孩子指针:

class BiNode{
public:
    char data;
    struct BiNode *lchild,*rchild;
};
  • 1
  • 2
  • 3
  • 4
  • 5

那么对于一个二叉树来说,只需要存放指向树根节点的指针即可,另外还需要声明二叉树的一些功能,比如遍历方法、求树高等(BiTree.h):

#ifndef BITREE_H_INCLUDED
#define BITREE_H_INCLUDED
#include<iostream>
#include <string>
using namespace std;
class BiNode{
public:
    char data;
    struct BiNode *lchild,*rchild;
};

class BiTree{
private:
    BiNode * root;
    int height;
    void pre_Order(BiNode * t);
    void in_Order(BiNode * t);
    void post_Order(BiNode * t);
    BiNode* create(string &s ,int&pos);
    void get_Height(BiNode *t,int h);
public:
    BiTree(){root=NULL;height=0;}
    ///按照前序遍历序列创建二叉树
    void createBiTree(string s);
    ///前序遍历二叉树
    void preOrder();
    ///中序遍历二叉树
    void inOrder();
    ///后序遍历二叉树(递归方法)
    void postOrder();
    ///后序遍历二叉树(使用栈的非递归方法)
    void postOrder1();
    ///层序遍历二叉树
    void levelOrder();
    ///求树的高度
    int getHeight();
    ///求两个节点的最大公共祖先
    void ancestor(char A,char B);
};



#endif // BITREE_H_INCLUDED
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

二叉树类的成员函数定义(BiTree.cpp)

#include "BiTree.h"
#include "queue"
#include "stack"
#include "vector"
#include<iostream>
using namespace std;
///递归创建二叉树,如果是#表示空节点
BiNode * BiTree::create(string &s,int &pos){
    ++pos;
    BiNode * t;
    if((unsigned)pos>=s.size())
        return NULL;
    else{
        if(s[pos]=='#')
            t=NULL;
        else{
            t=new BiNode;
            t->data=s[pos];
            t->lchild=create(s,pos);
            t->rchild=create(s,pos);
        }
        return t;
    }
}
///按照前序遍历序列创建二叉树
void BiTree::createBiTree(string s){
    int pos = -1;
    root=create(s,pos);
}
///前序遍历二叉树
void BiTree::preOrder(){
    pre_Order(root);
    cout<<endl;
}
void BiTree::pre_Order(BiNode * t){
    if(t!=NULL){
        cout<<t->data<<' ';
        pre_Order(t->lchild);
        pre_Order(t->rchild);
    }
}
///中序遍历二叉树
void BiTree::inOrder(){
    in_Order(root);
    cout<<endl;
}
void BiTree::in_Order(BiNode *t){
    if(t!=NULL){
        in_Order(t->lchild);
        cout<<t->data<<' ';
        in_Order(t->rchild);
    }
}
///后序遍历二叉树(递归方法)
void BiTree::postOrder(){
    post_Order(root);
    cout<<endl;
}
void BiTree::post_Order(BiNode *t){
    if(t!=NULL){
        post_Order(t->lchild);
        post_Order(t->rchild);
        cout<<t->data<<' ';
    }
}
///后序遍历二叉树(使用栈的非递归方法)
///后续遍历先遍历左子树,再遍历右子树,最后遍历根节点
///对于一个节点而言,先一直遍历到最左节点
///然后用r记录右子树是否遍历,如果没有遍历,则遍历右子树
void BiTree::postOrder1(){
    ///p表示当前树节点指针,
    ///r表示最近访问的树节点指针
    BiNode *p,*r;
    r = NULL;
    p = root;
    stack<BiNode*> my_stack;
    while(p!=NULL || !my_stack.empty()){
        if(p){
            ///一直走到树的最左边
            my_stack.push(p);
            p=p->lchild;
        }
        else{
            p=my_stack.top();
            ///如果右子树没有遍历,遍历右子树
            if(p->rchild!=NULL && p->rchild!=r){
                p=p->rchild;
                my_stack.push(p);
                ///注意这里需要向左转,因为如果不向左转,
                ///将会遍历右子树节点两边
                p=p->lchild;

            }
            ///否则遍历根节点
            else{
                p=my_stack.top();
                my_stack.pop();
                cout<<p->data<<' ';
                ///更新最近遍历的节点
                r=p;
                ///将遍历后的节点设为NULL,进行下一个节点的遍历
                p=NULL;
            }
        }
    }
    cout<<endl;
}
///使用队列进行层序遍历二叉树
void BiTree::levelOrder(){
    if(root==NULL)
        return;
    queue<BiNode*> q;
    q.push(root);
    while(!q.empty()){
        BiNode * t;
        t=q.front();
        q.pop();
        cout<<t->data<<' ';
        if(t->lchild!=NULL)
            q.push(t->lchild);
        if(t->rchild!=NULL)
            q.push(t->rchild);
    }
    cout<<endl;
}
///求树的高度
int BiTree::getHeight(){
    get_Height(root,0);
    return height;
}
void BiTree::get_Height(BiNode *t,int h){
    if(t!=NULL){
        ++h;
        if(h>height)
            height=h;
        get_Height(t->lchild,h);
        get_Height(t->rchild,h);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140

在这里定义的都是一些比较普通的函数,比较容易理解,值得一提的是,一般关于树的编程题适合用递归的方法来求解。 
此外,我这里还实现了后序遍历二叉树的非递归方法。这个需要重点讲解: 
对于一个节点来说,后序遍历意味着先左孩子,后右孩子,然后是该节点。那么非递归实现就需要使用一个栈来保存当前访问的节点。此外还需要用一个指针表示最近访问的节点指针,以区分右孩子是否访问过,如果右孩子访问过,那么最近访问的节点指针将会等于右孩子节点指针,这时就不必访问右孩子了,直接访问根节点即可。具体细节参见代码。 
细心的你可能会发现其实还有一个求最近公共祖先的函数没有实现,由于这个函数比较难,需要额外讲解,参见下一篇博客。

平衡二叉树是一种自平衡的二叉搜索树,它的左右子树的高度差不超过1。下面是平衡二叉树C++实现: ```cpp #include <iostream> using namespace std; // 平衡二叉树结点的定义 struct AVLNode { int data; // 数据 int height; // 高度 AVLNode* left; // 左子树 AVLNode* right; // 右子树 AVLNode(int val) : data(val), height(1), left(nullptr), right(nullptr) {} }; // 获取结点高度 int getHeight(AVLNode* node) { if (node == nullptr) { return 0; } return node->height; } // 获取平衡因子 int getBalanceFactor(AVLNode* node) { if (node == nullptr) { return 0; } return getHeight(node->left) - getHeight(node->right); } // 右旋 AVLNode* rightRotate(AVLNode* node) { AVLNode* leftChild = node->left; AVLNode* rightGrandChild = leftChild->right; leftChild->right = node; node->left = rightGrandChild; node->height = max(getHeight(node->left), getHeight(node->right)) + 1; leftChild->height = max(getHeight(leftChild->left), getHeight(leftChild->right)) + 1; return leftChild; } // 左旋 AVLNode* leftRotate(AVLNode* node) { AVLNode* rightChild = node->right; AVLNode* leftGrandChild = rightChild->left; rightChild->left = node; node->right = leftGrandChild; node->height = max(getHeight(node->left), getHeight(node->right)) + 1; rightChild->height = max(getHeight(rightChild->left), getHeight(rightChild->right)) + 1; return rightChild; } // 插入结点 AVLNode* insert(AVLNode* node, int val) { if (node == nullptr) { return new AVLNode(val); } if (val < node->data) { node->left = insert(node->left, val); } else if (val > node->data) { node->right = insert(node->right, val); } else { return node; } node->height = max(getHeight(node->left), getHeight(node->right)) + 1; int balanceFactor = getBalanceFactor(node); if (balanceFactor > 1 && val < node->left->data) { return rightRotate(node); } if (balanceFactor < -1 && val > node->right->data) { return leftRotate(node); } if (balanceFactor > 1 && val > node->left->data) { node->left = leftRotate(node->left); return rightRotate(node); } if (balanceFactor < -1 && val < node->right->data) { node->right = rightRotate(node->right); return leftRotate(node); } return node; } // 中序遍历 void inOrder(AVLNode* node) { if (node == nullptr) { return; } inOrder(node->left); cout << node->data << " "; inOrder(node->right); } // 测试 int main() { AVLNode* root = nullptr; int arr[] = { 9, 5, 10, 0, 6, 11, -1, 1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); for (int i = 0; i < n; i++) { root = insert(root, arr[i]); } inOrder(root); // 输出:-1 0 1 2 5 6 9 10 11 return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值