• 树的遍历


    #include<iostream>
    #include<memory.h> 
    #include<cstring>
    #include<queue>
    using namespace std;
    char* res[26];
    struct Node
    {
            Node* left;
            Node* right;
            char num;
            Node() { }; 
            Node(char c, Node* l = NULL, Node* r = NULL) 
            {
            	num=c;
            	left=l;
            	right=r;
    		}
    };
    
    Node* rebuild(char* pr,char* in,int len)
    {
       int i;
       Node* temp=new Node(*pr);
       if(len<=0)
            return NULL;
       //cout<<*pr;
       for(i=0;i<len;i++)
       {
               if(*pr==in[i])
               break;
       }
       temp->left=rebuild(pr+1,in,i);
       temp->right=rebuild(pr+i+1,in+i+1,len-i-1);
       return temp;
    }
    void PreOrder(Node* root)
    {
    	if(root)
    	{
    	cout<<root->num;
    	PreOrder(root->left);
    	PreOrder(root->right); 
        }
     } 
     void InOrder(Node* root)
     {
     	if(root)
     	{
     		InOrder(root->left);
    		cout<<root->num;
     		InOrder(root->right);
     	
    	 }
     }
     void PostOrder(Node* root)
     {
     	if(root)
     	{	
     		PostOrder(root->left);
     		PostOrder(root->right);
     		cout<<root->num;
    	 }
     }
     void LevelOrder(Node* root)
     {
     	queue<Node*> q;
     	if(root!=NULL)
     	q.push(root);
     	Node* temp;
     	while(!q.empty())
     	{
     		temp=q.front();
     		cout<<temp->num;
     		q.pop();
     		if(temp->left!=NULL)
     		q.push(temp->left);
     		if(temp->right!=NULL)
     		q.push(temp->right);
    	 }
     }
    int main()
    {
     char pr[26];    
     char in[26];
     cin>>pr;
     cin>>in;
     int len=strlen(pr);
     //cout<<len;
            //int len=cal(pr);
            //len=a.length();
            Node* root=rebuild(pr,in,len);
            //PreOrder(root);
            //cout<<endl;
            //InOrder(root);
            //cout<<endl;
            //PostOrder(root);
            //cout<<endl;
            LevelOrder(root);
            cout<<endl;
            return 0;
    }
    

      

  • 相关阅读:
    Tomcat 服务器体系结构
    tomcat的下载和启动
    tomcat解决端口号占用问题
    我的wmware
    Xshell的使用
    GCC的-wl,-rpath=参数
    Matlab图像处理(01)-Matlab基础
    CMake最好的学习资料
    使用valgrind进行内存泄漏和非法内存操作检测
    CLion提示can't find stdio.h等错误
  • 原文地址:https://www.cnblogs.com/xlqtlhx/p/7572094.html
Copyright © 2020-2023  润新知