• 数据结构之二叉树的建立与遍历


    已知一个按先序序列输入的字符序列,如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;
    }





  • 相关阅读:
    Genymotion安卓模拟器和VirtualBox虚拟机安装、配置、测试(win7_64bit)
    jQuery UI (15)图标
    CSS(01)CSS层叠样式表
    Jquery(12)Jquery Ajax跨域访问
    Jquery(13)Jquery this的指向
    Jquery(18)Jquery Cookie操作
    EntityFramework报错
    单例模式应用
    FormCollection的用法
    $.ajax、$.post[转]
  • 原文地址:https://www.cnblogs.com/lgh1992314/p/5835099.html
Copyright © 2020-2023  润新知