• MOOC 3.3 小白专场 树的同构


    // 树的同构
    /*
    	1. 二叉树的表示
    	2. 建二叉树
    	3. 同构判别
    */
    
    // 1. 二叉树的表示
    // 结构数组表示二叉树: 静态链表
    #define MaxTree 10
    #define ElementType char
    #define Tree int
    #define Null -1
    
    struct TreeNode 
    {
    	ElementType Element;
    	Tree Left;
    	Tree Right;
    }T1[MaxTree], T2[MaxTree];
    
    // 程序框架搭建
    int main()
    {
    	Tree R1, R2;
    	
    	R1 = BuildTree(T1);
    	R2 = BuildTree(T2);
    	if(Isomorphic(R1, R2))	printf("Yes
    ");
    	else	printf("No
    ");
    	
    	return 0;
    } 
    
    // 如何建立二叉树
    Tree BuildTree(struct TreeNode T[])
    {
    	...
    	scanf("%d
    ", &N);
    	if(N)
    	{
    		for(i = 0; i < N; ++ i)	check[i] = 0;
    		for(i = 0; i < N; ++ i)	
    		{
    			scanf("%c %c %c
    ", &T[i].Element, &cl, &cr);
    			/* 对cl的对应处理 */ 
    			if(cl != '-')
    			{
    				T[i].Left = cl - '0';
    				check[T[i].Left] = 1;
    			}
    			else	T[i].Left = Null;
    			/* 对cr的对应处理 */ 
    			if(cr != '-')
    			{
    				T[i].Right = cr - '0';
    				check[T[i].Right] = 1;
    			}
    			else	T[i].Right = Null;
    		}
    		for(i = 0; i < N; ++ i)
    			if(!check[i])	break;
    		Root = i;
    	}
    	return Root;
    } 
    
    int Isomorphic(Tree R1, Tree R2)
    {
    	/* both empty */
    	if((R1 == Null) && (R2 == Null))
    		return 1;
    	/* one of them is empty */
    	if(((R1 == Null) && (R2 != Null)) || ((R1 != Null) && R2 == Null))
    		return 0;
    	/* roots are different */
    	if(T1[R1].Element != T2[R2].Element)
    		return 0;
    	/* both have no left subtree */
    	if((T1[R1].Left == Null) && (T2[R2].Left == Null))
    		return Isomorphic(T1[R1].Right, T2[R2].Right);
    	/* no need to swap the left and the right */
    	if(((T1[R1].Left != Null) && (T2[R2].Left != Null)) &&
    	((T1[T1[R1].Left].Element) == (T2[T2[R2].Left].Element)))
    		return (Isomorphic(T1[R1].Left, T2[R2].Left) && 
    				Isomorphic(T1[R1].Right, T2[R2].Right));
    	else
    		return (Isomorphic(T1[R1].Left, T2[R2].Right) &&
    				Isomorphic(T1[R1].Right, T2[R2].Left));
    }
    

      

  • 相关阅读:
    Word批量转PDF或者图片
    sqlite3数据c/c++接口编程<linux,window>
    静态库和动态库
    QT信号和槽
    C程序编译过程
    Volatile关键字
    端口复用setsockopt
    深入理解epoll(转载)
    临时变量
    json学习随笔
  • 原文地址:https://www.cnblogs.com/mjn1/p/11460658.html
Copyright © 2020-2023  润新知