• 输入一颗二元查找树,将该树转换为它的镜像(递归解法)


    代码自己敲的,中间建树的时候遇到了麻烦,以前是先申请空间给根节点,这样的话根节点就需要单独处理。

    突发奇想用了下双重指针,对双重指针的作用和用法有了更好的理解。


    用递归解法做这个问题不难,主要熟悉了一下建树,打印树的代码。

    中间有调试代码,就不改了,方便看执行过程。


    #include<stdio.h>
    #include<stdlib.h>
    
    #define DEBUG(i) printf("Here " #i " is OK\n");
    
    typedef struct BSTreeNode
    {
    	int m_nValue;
    	struct BSTreeNode *m_pLeft;
    	struct BSTreeNode *m_pRight;
    }BSTreeNode;
    
    //====================================================================
    
    void iniTree(struct BSTreeNode ** mytree, int data);
    void printTree(struct BSTreeNode * mytree);
    void translate(struct BSTreeNode * mytree);
    
    //====================================================================
    
    int main()
    {
    
    	struct BSTreeNode * mytree = NULL;
    	int num, temp, i;
    	
    	printf("Please input how many numbers in your tree\n");
    	scanf("%d", &num);
    
    	for(i = 0; i < num; i++)
    	{
    		DEBUG(1);
    		scanf("%d", &temp);
    		iniTree(&mytree, temp);
    	}
    
    	translate(mytree);
    	
    	printTree(mytree);
    	DEBUG(0);
    	printf("Congratulations!\n");
    	return 0;
    }
    
    void iniTree(struct BSTreeNode ** mytree, int data)
    {
    	DEBUG(2);
    	if(*mytree == NULL)
    	{
    		*mytree = (struct BSTreeNode * )malloc(sizeof(BSTreeNode)); //here change the pointer to an addr, so ** is needed
    		(*mytree)->m_nValue = data;
    		(*mytree)->m_pLeft = NULL;
    		(*mytree)->m_pRight = NULL;
    		return;
    	}
    	else if((*mytree)->m_nValue >= data)
    		iniTree(&((*mytree)->m_pLeft), data);
    	else
    		iniTree(&((*mytree)->m_pRight), data);
    }
    
    void printTree(struct BSTreeNode * mytree)
    {
    	DEBUG(3);
    
    	if(mytree != NULL)
    	{
    		printf("%d\n", mytree->m_nValue);
    		if(mytree->m_pLeft != NULL)
    			printTree(mytree->m_pLeft);
    		if(mytree->m_pRight != NULL)
    			printTree(mytree->m_pRight);
    	}
    }
    
    void translate(struct BSTreeNode * mytree)
    {
    	if(!mytree)
    		return ;
    	if(mytree->m_pLeft)
    		translate(mytree->m_pLeft);
    	if(mytree->m_pRight)
    		translate(mytree->m_pRight);
    	struct BSTreeNode * temp;
    	temp = mytree->m_pLeft;
    	mytree->m_pLeft = mytree->m_pRight;
    	mytree->m_pRight = temp;
    }
    


  • 相关阅读:
    [bzoj1064][Noi2008]假面舞会
    [bzoj1503][NOI2004]郁闷的出纳员
    [bzoj1758][Wc2010]重建计划
    [bzoj1588][HNOI2002]营业额统计
    [bzoj2423][HAOI2010]最长公共子序列
    [3.26福建四校联考]
    [51nod1238]最小公倍数之和V3
    [bzoj2301] [HAOI2011]Problem b
    [hdu5608]function
    [51nod1239欧拉函数之和]
  • 原文地址:https://www.cnblogs.com/suzhou/p/3639014.html
Copyright © 2020-2023  润新知