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;
    }
    
  • 相关阅读:
    excel数据 入库mysql 和 mysql数据 导入excel文件
    gson和fastjson将json对象转换成javaBean 简单对照
    docker入门
    jdbc 事务
    关于Java 实现抽象类的抽象方法的特性的利用---面向切面
    try}-with-resources
    关于虚拟机加载类的先后顺序测试
    MySQL api
    JS 截取字符串-全是干货
    JS截取字符串常用方法详细整理
  • 原文地址:https://www.cnblogs.com/fangying7/p/4721546.html
Copyright © 2011-2022 走看看