zoukankan      html  css  js  c++  java
  • 二叉树相关操作

    #include <iostream>
    #include <vector>
    #include <deque>
    #include <map>
    #include <set>
    #include <string>
    #include <cstring>
    #include <cstdlib>
    
    using namespace std;
    
    typedef struct BinTree{
    	int data;
    	struct BinTree *left;
    	struct BinTree *right;
    }BinTree;
    
    /* 前序遍历 */
    void PreOrder(BinTree *root){
    	if(root == NULL)
    		return;
    
    	BinTree *p = root;
    	cout<<p->data<<endl;;
    	PreOrder(p->left);
    	PreOrder(p->right);
    }
    
    /*  中序遍历 */
    void InOrder(BinTree *root){
    	if(root == NULL)
    		return;
    	
    	BinTree *p = root;
    	InOrder(p->left);
    	cout<<p->data<<endl;;
    	InOrder(p->right);
    }
    
    /* 后序遍历 */
    void PostOrder(BinTree *root){
    	if(root==NULL)
    		return;
    	
    	BinTree *p = root;
    	PostOrder(p->left);
    	PostOrder(p->right);
    	cout<<p->data<<endl;;
    }
    
    /* 按照层序遍历方法遍历二叉树,使用一个队列来辅助 */
    void BreadthFirst(BinTree *root){
    	if(root == NULL)
    		return;
    	deque<BinTree *> q;
    	q.push_back(root);
    
    	BinTree *p;
    	while(!q.empty()){
    		p = q.front();
    		q.pop_front();
    
    		cout<<p->data;
    
    		if(p->left)
    			q.push_back(p->left);
    
    		if(p->right)
    			q.push_back(p->right);
    	}
    }
    
    /* 按照前序遍历的方式构造二叉树 */
    void CreateBinTree(BinTree **root){
    	
    	int data;
    	cin>>data;
    	if(data == 0){
    		*root = NULL;
    	}else{
    		*root = (BinTree *)malloc(sizeof(BinTree));
    		if(!*root)
    			return;
    		(*root)->data = data;			
    		CreateBinTree(&(*root)->left);
    		CreateBinTree(&(*root)->right);
    	}
    }
    
    
    int main(){
    	BinTree *root;
    	CreateBinTree(&root);
    	BreadthFirst(root);
    	return 0;
    }
    
  • 相关阅读:
    【Linux】grep or
    win10查看WiFi密码
    【WPF】Border有显示模糊的情况
    【Spark】配置项spark.network.timeout 的单位是什么
    【Linux】free命令中 free与 available 的区别
    Spark2.3配置项
    java获取jar包执行路径
    编译 thrift-0.14.2 的 C++ 版本
    拉端保障方案
    编译运行ebpf代码的流水账
  • 原文地址:https://www.cnblogs.com/fangying7/p/4721546.html
Copyright © 2011-2022 走看看