zoukankan      html  css  js  c++  java
  • 数据结构之二叉树的建立与遍历

    已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后方式遍历二叉树最后求出叶子节点个数和二叉树深度

    #include<iostream>
    #include<queue>
    #include <cstdlib>
    #include <cstdio>
    using namespace std;
    typedef struct BiNode
    {
    	char data;
    	struct BiNode *left;
    	struct BiNode *right;
    }BiNode, *BiTree;
    int sum = 0;
    void CreateBinaryTree(BiTree &T)//二叉树建立   abc,,de,g,,f,,,
    {
    	//T = (BiNode*) malloc (sizeof(BiNode));
    	T = new BiNode;
    	cin >> T->data;
    	if(T->data == ',') 
    	{
    		T = NULL; 
    	}
    	if(T != NULL)
    	{
    		CreateBinaryTree(T->left);
    		CreateBinaryTree(T->right);
    	}
    }
    void PreOrder(BiTree T)//前序遍历
    {
    	if(T != NULL)
    	{
    		cout << T->data;
    		PreOrder(T->left);
    		PreOrder(T->right);
    	}
    }
    void InOrder(BiTree T)//中序遍历
    {
    	if(T != NULL)
    	{
    		InOrder(T->left);
    		cout << T->data;
    		InOrder(T->right);
    	}
    }
    void PostOrder(BiTree T)//后序遍历
    {
    	if(T != NULL)
    	{
    		PostOrder(T->left);
    		PostOrder(T->right);
    		cout << T->data;
    	}
    }
    void LevOrder(BiTree T)//层次遍历
    {
    	if(T != NULL)
    	{
    		BiTree p = T;
    		queue<BiTree>que;
    		que.push(p);
    		while(!que.empty())
    		{
    			p = que.front();
    			cout << p->data;
    			que.pop();
    			if(p->left != NULL)
    			{
    				que.push(p->left);
    			}
    			if(p->right != NULL)
    			{
    				que.push(p->right);
    			}
    		}
    	}
    }
    int Size(BiTree T)//计算二叉树节点数
    {
    	if(T)
    	{
    		if(T->left == NULL && T->right == NULL)
    		{
    			sum++;
    		}
    		Size(T->left);
    		Size(T->right);
    	}
    	return sum;
    }
    int Deep(BiTree T)//计算二叉树深度
    {
    	int m, n;
    	if(T == NULL) return 0;
    	m = Deep(T->left);
    	n = Deep(T->right);
    	if(m > n) return m + 1;
    	else return n + 1;
    }
    int main(void)
    {
    	BiTree T;
    	CreateBinaryTree(T);
    
    	cout << "前序遍历结果为:" << endl;
    	PreOrder(T);
    	cout << endl << endl;
    
    	cout << "中序遍历结果为:" << endl;
    	InOrder(T);
    	cout << endl << endl;
    
    	cout << "后序遍历结果为:" << endl;
    	PostOrder(T);
    	cout << endl << endl;
    
    	cout<<"层次遍历结果为:"<<endl;
    	LevOrder(T);
    	cout << endl << endl;
    
    	cout << "二叉树叶节点个数为:" << Size(T)<<endl;
    	cout << "二叉树深度数为:" << Deep(T) << endl;
    	system("pause");
    	return 0;
    }





  • 相关阅读:
    [UE4]九宫格图片拉伸
    [UE4]IsValid方法妙用
    [UE4]蓝图函数库
    [UE4]创建KillInfoPanel
    [UE4]条件语句Select
    [UE4]控件模板参数
    [UE4]控件模板
    [UE4]不推荐的UI更新方式
    [UE4]事件驱动的UI更新:事件调度器
    [UE4]更新UI的三种方式
  • 原文地址:https://www.cnblogs.com/lgh1992314/p/5835099.html
Copyright © 2011-2022 走看看