二叉树专题

二叉树 

(一)二叉树的三种遍历方式:

前序遍历 : 1  2  4  5  3  6  7 ; 中序遍历 : 4  2  5  1  6  3  7 ;  后序遍历 : 4  5  2  6  7  3  1 ;

本质是在递归序的基础上打印时机的不同,可以使用栈来实现三种遍历。深度优先遍历(DFS)

(二)各种遍历的非递归实现

struct Node {
	int value;
	Node *left;
	Node *right;
};

前序遍历:

1.先定义一个栈,把压入栈 ; 2. 弹出栈顶元素,并且打印出来;3.如果弹出的栈顶元素有右节点,将该节点压入到栈中,如果有左节点,后向栈中压入左节点;中左右顺序,因为是栈,所以先压入右,后压入左。

static void preOrderUnRecur(Node *head) {
	
	if (head != nullptr) {
		stack<Node*> stack;
		stack.push(head);
		while (!stack.empty()) {
			head = stack.top();
			printf("%d\0", head->value);
			stack.pop();
			if (head->right != nullptr) {
				stack.push(head->right);
			}
			if (head->left != nullptr) {
				stack.push(head->left);
			}
		}
	}
}

2.后序遍历,左中右,把前序遍历的基础上调整左右子树压入顺序,期间不进行打印,并且开辟额外的栈,来保存节点,最后统一输出便是左右中。

3.中序遍历:把整个树左边界化,从根节点开始一直沿着左树压入栈,如果有右子树依然是按照左边界的方式重复。

#include <iostream>
#include <stack>
using namespace std;

struct TreeNode {
    int value;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int v) : value(v), left(nullptr), right(nullptr) {}
};

void preOrderTraversal(TreeNode* root) {
    if (root == nullptr) return;
    stack<TreeNode*> s;
    s.push(root);
    while (!s.empty()) {
        TreeNode* node = s.top();
        s.pop();
        cout << node->value << " ";
        if (node->right) s.push(node->right);
        if (node->left) s.push(node->left);
    }
}

void inOrderTraversal(TreeNode* root) {
    stack<TreeNode*> s;
    TreeNode* current = root;
    while (current != nullptr || !s.empty()) {
        while (current != nullptr) {
            s.push(current);
            current = current->left;
        }
        current = s.top();
        s.pop();
        cout << current->value << " ";
        current = current->right;
    }
}

void postOrderTraversal(TreeNode* root) {
    if (root == nullptr) return;
    stack<TreeNode*> s1, s2;
    s1.push(root);
    while (!s1.empty()) {
        TreeNode* node = s1.top();
        s1.pop();
        s2.push(node);
        if (node->left) s1.push(node->left);
        if (node->right) s1.push(node->right);
    }
    while (!s2.empty()) {
        cout << s2.top()->value << " ";
        s2.pop();
    }
}

int main() {
    TreeNode* root = new TreeNode(1);
    root->left = new TreeNode(2);
    root->right = new TreeNode(3);
    root->left->left = new TreeNode(4);
    root->left->right = new TreeNode(5);

    cout << "Pre-order traversal: ";
    preOrderTraversal(root);
    cout << endl;

    cout << "In-order traversal: ";
    inOrderTraversal(root);
    cout << endl;

    cout << "Post-order traversal: ";
    postOrderTraversal(root);
    cout << endl;

    return 0;
}

可以使用队列来实现三种遍历。广度优先遍历(BFS)

1.定义一个队列,先压入根节点。然后分别压入先左后右子树,依次弹出。本例输出:1,2,3,4,5,6,7

bool leveltraverse(Btree T){
    Btree p;
    if(!T)
        return false;
    queue<Btree>Q; //创建一个队列,指针类型
    Q.push(T); //根指针入队
    while(!Q.empty()){ //如果队列不空
        p=Q.front();//取出队头元素
        Q.pop(); //队头元素出队
        cout<<p->data<<"  ";
        if(p->lchild)
            Q.push(p->lchild); //左孩子指针入队
        if(p->rchild)
            Q.push(p->rchild); //右孩子指针入队
    }
    return true;
}
#include <iostream>
#include <queue>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

// 前序遍历
void preOrder(TreeNode* root) {
    if (root == nullptr) return;
    
    queue<TreeNode*> q;
    q.push(root);
    
    while (!q.empty()) {
        TreeNode* node = q.front();
        q.pop();
        
        cout << node->val << " ";
        
        if (node->left) q.push(node->left);
        if (node->right) q.push(node->right);
    }
}

// 中序遍历
void inOrder(TreeNode* root) {
    if (root == nullptr) return;
    
    queue<TreeNode*> q1;
    queue<int> q2; // 用于存储节点访问状态,0表示未访问,1表示已访问
    q1.push(root);
    q2.push(0);
    
    while (!q1.empty()) {
        TreeNode* node = q1.front();
        int visited = q2.front();
        q1.pop();
        q2.pop();
        
        if (node == nullptr) continue;
        
        if (visited == 0) {
            q1.push(node->left);
            q2.push(0);
            q1.push(node);
            q2.push(1);
            q1.push(node->right);
            q2.push(0);
        } else {
            cout << node->val << " ";
        }
    }
}

// 后序遍历
void postOrder(TreeNode* root) {
    if (root == nullptr) return;
    
    queue<TreeNode*> q1;
    queue<int> q2; // 用于存储节点访问状态,0表示未访问,1表示左子节点已访问,2表示右子节点已访问
    q1.push(root);
    q2.push(0);
    
    while (!q1.empty()) {
        TreeNode* node = q1.front();
        int visited = q2.front();
        q1.pop();
        q2.pop();
        
        if (node == nullptr) continue;
        
        if (visited == 0) {
            q1.push(node);
            q2.push(1);
            q1.push(node->left);
            q2.push(0);
            q1.push(node->right);
            q2.push(0);
        } else if (visited == 1) {
            q1.push(node);
            q2.push(2);
        } else {
            cout << node->val << " ";
        }
    }
}

int main() {
    TreeNode* root = new TreeNode(1);
    root->left = new TreeNode(2);
    root->right = new TreeNode(3);
    root->left->left = new TreeNode(4);
    root->left->right = new TreeNode(5);
    
    cout << "Preorder traversal: ";
    preOrder(root);
    cout << endl;
    
    cout << "Inorder traversal: ";
    inOrder(root);
    cout << endl;
    
    cout << "Postorder traversal: ";
    postOrder(root);
    
    return 0;
}

哈夫曼编码

#include<iostream>
#include<cstring>
using namespace std;
#define MAXBIT    100
#define MAXVALUE  0x3f3f3f3f
#define MAXLEAF   30
#define MAXNODE   MAXLEAF*2 -1

typedef struct{ //节点结构体
    double weight; //权值
    int parent; //双亲
    int lchild; //左孩子
    int rchild; //右孩子
    char value; //字符信息 
}HNodeType;        

typedef struct{ //编码结构体
    int bit[MAXBIT];
    int start;
}HCodeType;
HNodeType HuffNode[MAXNODE]; //定义一个节点结构体数组
HCodeType HuffCode[MAXLEAF]; //定义一个编码结构体数组

void HuffmanTree (HNodeType HuffNode[], int n){ //构造哈夫曼树
    int x1,x2; //x1、x2:最小、次小权值节点的编号
    double m1,m2; //m1、m2:最小、次小权值节点的权值
    for(int i=0;i<2*n-1;i++){//初始化
        HuffNode[i].weight=0;
        HuffNode[i].parent=-1;
        HuffNode[i].lchild=-1;
        HuffNode[i].rchild=-1;
    }
    cout<<"Please input value and weight of leaf node :"<<endl;
	for(int i=0;i<n;i++)//输入n个叶子的信息和权值
        cin>>HuffNode[i].value>>HuffNode[i].weight;
    for(int i=0;i<n-1;i++){//执行n-1次合并
        m1=m2=MAXVALUE;
        x1=x2=0;
        for(int j=0;j<n+i;j++){//找权值最小和次小、且无父节点的两个节点
            if(HuffNode[j].weight<m1&&HuffNode[j].parent==-1){
                m2=m1;
                x2=x1;
                m1=HuffNode[j].weight;
                x1=j;
            }
            else if(HuffNode[j].weight<m2&&HuffNode[j].parent==-1){
                m2=HuffNode[j].weight;
                x2=j;
            }
        }
        HuffNode[x1].parent=n+i; //更新5个信息,两个结点的父亲为新节点,新节点的权值和两个孩子 
        HuffNode[x2].parent=n+i;
        HuffNode[n+i].weight=m1+m2;
        HuffNode[n+i].lchild=x1;
        HuffNode[n+i].rchild=x2;
        cout<<"x1.weight and x2.weight in round "<<i+1<<"\t"<<HuffNode[x1].weight<<"\t"<<HuffNode[x2].weight<<endl; /* 用于测试 */
    }
}

void HuffmanCode(HCodeType HuffCode[],int n){ //哈夫曼树编码
    HCodeType cd; //定义一个临时变量来存放求解编码时的信息
    int c,p;
	for(int i=0;i<n;i++){
        cd.start=n-1;
        c=i;
        p=HuffNode[c].parent;
        while(p!=-1){
            if(HuffNode[p].lchild==c)
                cd.bit[cd.start]=0;
            else
                cd.bit[cd.start]=1;
            cd.start--; //前移一位
            c=p;
            p=HuffNode[c].parent; //设置下一循环条件
        }
        //把叶子节点的编码信息从临时编码cd中复制出来,放入编码结构体数组
        for(int j=cd.start+1;j<n;j++)
        	HuffCode[i].bit[j]=cd.bit[j];
        HuffCode[i].start=cd.start;
    }
}

int main(){
    int n;
    cout<<"Please input n:"<<endl;
    cin>>n;
    HuffmanTree(HuffNode,n); //构造哈夫曼树
    HuffmanCode(HuffCode,n); //哈夫曼编码
    for(int i=0;i<n;i++){ //输出所有哈夫曼编码
        cout<<HuffNode[i].value<<": Huffman code is: ";
        for(int j=HuffCode[i].start+1;j<n;j++)
            cout<<HuffCode[i].bit[j];
        cout<<endl;
    }
    return 0;
}
/*测试数据 
6
a 0.05
b 0.32
c 0.18
d 0.07
e 0.25
f 0.13
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

༄yi笑奈何

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值